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

Subroutines को References Pass करना

एक reference pass करना बड़ा data copy करने से बचाता है और एक subroutine को original बदलने देता है।

Subroutines को References Pass करना

जब आप arrays या hashes सीधे pass करते हैं, Perl इन्हें @_ में एक list में flatten कर देता है, इसलिए दो arrays merge हो जाएँगे और आप boundary खो देंगे। References pass करना हर structure को intact और cheaply pass होने लायक रखता है। Subroutine reference के जरिए पढ़ सकता है और, क्योंकि यह एक copy नहीं है, इसके जरिए किए changes caller को दिखते हैं।

Note: यह check करने के लिए ref($arg) eq ARRAY इस्तेमाल करें कि caller ने actually एक array reference pass की है।

उदाहरण: Passing references to subroutines

perl
use strict;
use warnings;

sub flat_count { return scalar @_; }
sub ref_counts { my ($p, $q) = @_; return scalar(@$p) . " and " . scalar(@$q); }
sub add_item   { my ($list, $item) = @_; push @$list, $item; return; }

my @first  = (1, 2, 3);
my @second = (4, 5);
print "flattened count: ", flat_count(@first, @second), "\n";
print "with references: ", ref_counts(\@first, \@second), "\n";
add_item(\@first, 99);
print "first is now: @first\n";
my @copy = @first;
push @copy, 100;
print "copy: @copy\n";
print "original: @first\n";

# Output:
# flattened count: 5
# with references: 3 and 2
# first is now: 1 2 3 99
# copy: 1 2 3 99 100
# original: 1 2 3 99
{# 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. दो arrays सीधे pass करना और उम्मीद करना कि वे separate रहेंगे
  2. accidentally एक reference के जरिए data modify करना
  3. एक reference copy करना और सोचना कि आपने data copy किया
चैप्टर सारांश
  • सीधे pass किए गए Arrays flatten हो जाते हैं
  • इसे intact रखने के लिए \@array pass करें
  • एक reference के जरिए changes caller को प्रभावित करते हैं
  • arguments validate करने के लिए ref इस्तेमाल करें
🔒

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.