There are two ways to pass arrays to subs. In the first you pass the elements of the array individually.
sub printArray { for my $element ( @_ ) { print $element, "\n"; } } .... my @array = (1 ,2 ,3 4, 5); printArray( @array );
Will print the numbers 1 to 5. However, this method doesn't work very well if you want to pass two or more arrays and keep the elements seperate.
To do this, you need to pass references to the arrays to the sub and then dereference them in the sub to get acces to the elements.
#! perl -sw use strict; sub printArrays { my ($arrayRef1, $arrayRef2) = @_; for my $element ( @{$arrayRef1} ) { print 'Array1 element: ', $element, "\n"; } for my $element ( @$arrayRef2 ) { print 'Array2 element: ', $element, "\n"; } #another way showing a few more things. for ( my $i=0; $i <= $#{$arrayRef1}; $i++ ) { print "Array1[$i] = ", $$arrayRef1[$i], "\n"; } } my @ary1 = (1, 2, 3, 4, 5); my @ary2 = ('a', 'b', 'c', 'd', 'e'); printArrays( \@ary1, \@ary2 );
This prgram produces the following output
c:\test>test Array1 element: 1 Array1 element: 2 Array1 element: 3 Array1 element: 4 Array1 element: 5 Array2 element: a Array2 element: b Array2 element: c Array2 element: d Array2 element: e Array1[0] = 1 Array1[1] = 2 Array1[2] = 3 Array1[3] = 4 Array1[4] = 5 c:\test>
Hopefully this will get you started. To understand more, read perlsub, then if you are interested in learning more, perlref and perlreftut
Have fun.
In reply to Re: passing arrays to asubroutine
by BrowserUk
in thread passing arrays to asubroutine
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |