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.


Cor! Like yer ring! ... HALO dammit! ... 'Ave it yer way! Hal-lo, Mister la-de-da. ... Like yer ring!

In reply to Re: passing arrays to asubroutine by BrowserUk
in thread passing arrays to asubroutine by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.