Subroutine References का परिचय
Subroutines variables में store हो सकते हैं और बाद में call हो सकते हैं, जो आपको behaviour pass around करने देता है।
In this page:
Subroutine References
आप sub name { ... } से एक named subroutine define करते हैं और इसके नाम से इसे call करते हैं; arguments array @_ में आते हैं। sub { ... } लिखा एक anonymous subroutine, एक scalar में store हो सकता है और $code->(args) या &$code(args) से call हो सकता है। hashes या arrays में code references store करना आपको simple dispatch tables देता है।
Note:
एक value वापस भेजने के लिए return इस्तेमाल करें, नहीं तो एक subroutine अपने last evaluated expression की value return करता है।
उदाहरण: Subroutine references
use strict;
use warnings;
sub add { my ($x, $y) = @_; return $x + $y; }
my $adder = \&add;
print "add via ref: ", $adder->(2, 3), "\n";
my $square = sub { my $n = shift; return $n * $n; };
print "square: ", $square->(7), "\n";
my %ops = (
plus => sub { $_[0] + $_[1] },
minus => sub { $_[0] - $_[1] },
times => sub { $_[0] * $_[1] },
);
for my $name (sort keys %ops) {
print "$name: ", $ops{$name}->(6, 3), "\n";
}
# Output:
# add via ref: 5
# square: 49
# minus: 3
# plus: 9
# times: 18
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- parentheses और arrow के बिना एक code reference call करना
- यह भूल जाना कि arguments @_ में हैं और automatically named नहीं हैं
- parentheses के साथ \&name() लिखना और इसे reference करने की बजाय function call करना
चैप्टर सारांश
- sub { } एक anonymous subroutine बनाता है
- \&name एक named वाला reference करता है
- $code->(args) इसे call करता है
- Code refs के Hashes dispatch tables बनाते हैं
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: