in reply to reference array and pass ref to sub
Perl is also different in many other respects to other languages. A variable like @array can have a list context as well as a scalar context. If you had written my $array = @array, $array would have been the number of elements in the list @array. In Perl, each type of variable has its own namespace, so $list=@list is completely fine.
To take a reference to a list, use: my listRef = \@list. This is "sort of" like an address of an array in C.
In the below code, I send a reference to a list into a sub. @$listRef expands that reference back into the original list.
One of the really magic things about Perl is that it is almost NEVER necessary to use something like: for ( my $i=1; $i<=$size; $i++ ). There are situations for this, but only perhaps once per 5K+ lines of Perl code - this is a rare duck! I did print an "index" in one situation below, but note that it is NOT the looping variable!
#!/usr/bin/perl -w use strict; my @list= (1,2,3,4,5); printListRef(\@list); sub printListRef { my $listRef = shift; ########### easy way ######## print "easy way\n"; print "@$listRef\n"; ############################# #### another way (ugly)########### print "\nugly index stuff way\n"; my $i =0; foreach my $item (@$listRef) { print "list element[$i]=$item\n"; $i++; } ########## perl way for item per line ### print "\nperl way with one item per line\n"; print join("\n",@$listRef),"\n"; } ## it might not be apparent, but the __END__ ##line stopped the compilation. Another cool this about Perl. __END__ prints: easy way 1 2 3 4 5 ugly index stuff way list element[0]=1 list element[1]=2 list element[2]=3 list element[3]=4 list element[4]=5 perl way with one item per line 1 2 3 4 5
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: reference array and pass ref to sub
by Tanktalus (Canon) on Mar 07, 2009 at 00:15 UTC | |
by Marshall (Canon) on Mar 07, 2009 at 01:57 UTC |