Closures को समझें
एक anonymous subroutine उन variables को याद रखता है जो इसके बनने के वक्त scope में थे।
In this page:
Closures
जब एक anonymous subroutine surrounding scope से एक my variable इस्तेमाल करता है, Perl उस variable को जब तक subroutine exist करे तब तक alive रखता है। ऐसा subroutine बनाने वाले function की हर call को इस variable की अपनी fresh copy मिलती है। यह आपको बिना किसी package machinery के counters, generators, और दूसरे छोटे objects बनाने देता है।
Note:
Perl data तब free करता है जब इसका last reference गायब हो जाता है, इसलिए एक closure अपने captured variables alive रखता है।
उदाहरण: Closures
use strict;
use warnings;
sub make_counter {
my $count = shift;
return sub { return $count++; };
}
my $c1 = make_counter(1);
my $c2 = make_counter(100);
print "c1: ", $c1->(), " ", $c1->(), " ", $c1->(), "\n";
print "c2: ", $c2->(), " ", $c2->(), "\n";
print "c1 again: ", $c1->(), "\n";
my @subs;
for my $i (1 .. 3) {
push @subs, sub { return $i * 10; };
}
print "loop closures: ", join(", ", map { $_->() } @subs), "\n";
# Output:
# c1: 1 2 3
# c2: 100 101
# c1 again: 4
# loop closures: 10, 20, 30
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- एक loop में बने हर closure से एक variable share करने की उम्मीद करना
- यह भूल जाना कि factory की हर call एक नया independent counter बनाती है
- एक global variable इस्तेमाल करना जब एक captured my variable safer होता
चैप्टर सारांश
- Closures surrounding my variables capture करते हैं
- हर creation की अपनी copy होती है
- Captured variables closure के साथ alive रहते हैं
- Closures counters और generators बनाते हैं
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: