in reply to Re: Passing an array to a subroutine
in thread Passing an array to a subroutine

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>

Replies are listed 'Best First'.
Re: Re: Re: Passing an array to a subroutine
by suaveant (Parson) on Jul 31, 2001 at 21:04 UTC
    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
        Why would $hdr be empty? Two possibilities. First, it's a blank line. chomping it will remove the newline, leaving a possibly empty string. The second possibility is that the open failed. Here's a better error line:

        open(FILE, $data) or die "Can't open ($data): $!";

        That gives you the name of the file, surrounded by non-whitespace characters as a sanity check, along with the system error message. You'll have better luck if you let Perl help you.

        Update: If it's not a file, don't open it. open works on files (in the Unix sense). If you have the data you want to munge already in an array or a scalar, use split or a regex to get at it. That's the problem.