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

Subroutine References का परिचय

Subroutines variables में store हो सकते हैं और बाद में call हो सकते हैं, जो आपको behaviour pass around करने देता है।

In this page:

  1. Subroutine References

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

perl
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
{# 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. parentheses और arrow के बिना एक code reference call करना
  2. यह भूल जाना कि arguments @_ में हैं और automatically named नहीं हैं
  3. 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:

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.