in reply to Passing an array to a subroutine

You pretty much had it right before...
#open(FILE, my $aref); #or die "Cannot open: $file\n";
except your my $aref in the open is overriding the
my ($aref} = @_;
at the head of your subroutine, so aref in the open is undef... do
open(FILE, $aref) or die "Cannot open: $file\n"; $line = <FILE>;
and you should be golden

<> works on @ARGV, not @_... if there is nothig it @ARGV it will read from STDIN

Update oh yes, the while loop would also use <FILE> instead of <>

                - Ant

Replies are listed 'Best First'.
Re: Re: Passing an array to a subroutine
by gisrob (Novice) on Jul 31, 2001 at 19:38 UTC
    Thanks. I changed the code as you suggested, but my output files are empty. I ran this under the debugger with a break at that sub routine. When I type p @_ I get all the values in the array, but then p $aref is empty, and the rest of the routine, while it runs, is running on empty data. Thoughts?
    sub subgen { my $aref = @_; my($cur_segno) = 0; my(@sst) = (); open(FILE, $aref); #or die "Cannot open: $file\n"; my $hdr = <FILE>; #read in the first line chomp $hdr; my @colnames = split /, ?/, $hdr; #split the header into an array open GENFILE, '>genfile.txt'; open INFOFILE, '>infofile.txt'; my $sst_mean; my %fronts; while (<FILE>) { <snip>
      hmmm keep the () around your my $aref line...
      my ($aref) = @_; #or do my $aref = $_[0]; #or my $aref = shift;
      shift defaults to shift the first value off @_ if you don't supply an array argument.

                      - Ant

        Here's the current code. When I run it under the debugger, all is well until I get to the my $hdr line. When I step through this and (in the debugger) type p $hdr, it returns nothing; the same is true when I type p @colnames even though p $data returns the whole data array. I'm new at this, so I don't really understand how the FILEHANDLEs work. Even though this syntax seems correct, it doesn't seem to really open that array. I'm lost.
        sub subgen { my($data) = shift; chomp($data); my($cur_segno) = 0; my(@sst) = (); open(FILE, $data); # or die "Cannot open: @data\n"; my $hdr = <FILE>; #read in the first line chomp $hdr; my @colnames = split /, ?/, $hdr; #split the header into an array