Subroutines को References Pass करना
एक reference pass करना बड़ा data copy करने से बचाता है और एक subroutine को original बदलने देता है।
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- दो arrays सीधे pass करना और उम्मीद करना कि वे separate रहेंगे
- accidentally एक reference के जरिए data modify करना
- एक 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: