in reply to Re: printing sub return values to a file
in thread printing sub return values to a file

Hi cdarke!
I made a change to the subroutine, but it only returns the first element.
Any ideas on how I can get around that to return the all of the elements?
sub get_oligo_seqs{ my ($fh) = shift; while(<$fh>){ my @fields = split /\t/; my $oligos = $fields[1]; push(my @seqs,($oligos)); return "@seqs\n"; } }

LomSpace

Replies are listed 'Best First'.
Re^3: printing sub return values to a file
by toolic (Bishop) on Nov 19, 2009 at 21:03 UTC
    The following will loop through all lines of the input file (assuming you opened the file prior to calling the sub), populate the array, then return the array. I think your code was exiting the sub after reading only one line.
    sub get_oligo_seqs{ my ($fh) = shift; my @seqs; while(<$fh>){ my @fields = split /\t/; my $oligos = $fields[1]; push(@seqs,($oligos)); } return @seqs; }

      That clobbers the parent's $_. Fixed:

      sub get_oligo_seqs{ my ($fh) = shift; my @seqs; while(my $rec = <$fh>){ my @fields = split /\t/, $rec; my $oligos = $fields[1]; push(@seqs,($oligos)); } return @seqs; }

      This seems simpler to me:

      sub get_oligo_seqs{ my ($fh) = shift; my @seqs; while(my $rec = <$fh>){ push @seqs, ( split /\t/, $rec )[1]; } return @seqs; }

      Why stop there?

      sub get_oligo_seqs{ my ($fh) = shift; return map { ( split /\t/ )[1] } <$fh>; }
      Toolic!
      Thanks!
      LomSpace