← Back to Perl Course | Chapter 6: References | Lesson 7 of 7

Closures को समझें

एक anonymous subroutine उन variables को याद रखता है जो इसके बनने के वक्त scope में थे।

In this page:

  1. Closures

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

perl
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
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक loop में बने हर closure से एक variable share करने की उम्मीद करना
  2. यह भूल जाना कि factory की हर call एक नया independent counter बनाती है
  3. एक 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.