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

Suppose I have declared severals subroutines in a code and I want to print all the values of a "for" loop used in one of the subroutines

part of the code where I want to get the print

sub upstream my ($i,$j,$k, $up, $in, $dna, $size, $upstream, @temp, @pos,@neg, @genome_data ); . . . . . . @genome_data = @_; for ($i=0; $i<@genome_data; $i++) { $genome_data[$i]{GENOME_SIZE} = $size; }
end of part of code

I want to print $genome_data$i{GENOME_SIZE} for every i ..... How can i do that

Thanks

Replies are listed 'Best First'.
Re: printing in subroutines
by kcott (Archbishop) on Sep 11, 2013 at 21:29 UTC

    G'day ashprog,

    Please put your code in <code>...</code> tags. "Writeup Formatting Tips" explains about this.

    The code you've posted does not declare a subroutine: it may be invalid syntax; it certainly doesn't do what you appear to think it does. Take a look at "perlintro: Writing subroutines".

    I expect the answer you're looking for is:

    print $_->{GENOME_SIZE} for @genome_data;

    [Disclaimer: I've had to make assumptions about what your real code might look like. If you correct the code you've posted, my answer may change.]

    -- Ken

Re: printing in subroutines
by GotToBTru (Prior) on Sep 11, 2013 at 21:29 UTC
    You have the syntax of the for loop already, so I'm going to guess the problem is printing the array outside of the subroutine in which it is populated - correct? Define the array at the main level, and pass a reference to it to the subroutine. Then, any changes made to the array in the subroutine will be made to the original. See perlreftut
    use strict; use warnings; my (@genome_data_g); upstream(\@genome_data_g); foreach $datapoint (@genome_data_g) { print "$datapoint\n"; } sub upstream { my $array_ref = shift; $$array_ref[1] = 'some value'; }

    Update: removed & from subroutine call (line 5).