Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

passing arrays to subroutines

by indapa (Monk)
on Apr 10, 2001 at 02:15 UTC ( #71188=perlquestion: print w/replies, xml ) Need Help??

indapa has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am passing two arrays to a subroutine and getting some wierd results. Here is my code snippet
@MLR_file = <MLR>; # read in file 1 data $MLR_file[2] =$MLR_file[1] = $MLR_file[0]; # modify it @MLR_file2 = <MLR2>; #read in set2 data $MLR_file2[2] =$MLR_file2[1] = $MLR_file2[0]; # modify it &printFile (@MLR_file, @MLR_file2); sub printFile { #print the contents of each array to the correct ouput file my @file = $_[0]; my @file2 = $_[1]; foreach $line(@file) { print OUT "$line"; } foreach $line(@file2) { print OUT2 "$line"; }
Basically I'm reading files into an array, modifying them, and writing the new output to a new file. The trouble is that my new output file(s) only has one line in it (there should be 96 lines of output).

I tried passing the arguments as references, without really know why. When I more my ouput file(s) looked like this

ARRAY(0xd3a2c) ARRAY(0xd3a98)
Any explaination on this would be appreciated. Thank you.

Replies are listed 'Best First'.
Re: passing arrays to subroutines
by Masem (Monsignor) on Apr 10, 2001 at 02:20 UTC
    With two arrays, you do need to pass as references, otherwise there's no way to tell where one array ends, and the other begins. Once in the subroutine as references, you need to de-reference them to get at the values...
    my @array1 = ( 1..6 ); my @array2 = ( 7..12 ); my_sub( \@array1, \@array2 ); sub my_sub { my ( $ref1, $ref2 ) = @_; # get these as references... @arr1 = @$ref1; @arr2 = @$ref2; # either deference into new variables... print @arr1, @arr2; print @$ref1, @$ref2; # or just use the reference directly }
    Refer to perlref for more information.
    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
Re: passing arrays to subroutines
by ok (Beadle) on Apr 10, 2001 at 02:21 UTC
    Did a search (on perlmonks) for "passing arrays." Came up with this.

    Search and your life will be sublime.
      Thanks for the replies, I have gained enlightenment.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://71188]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2019-12-15 15:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?