in reply to How to store the indexes of a array

Here is how I interpret your question (and answer it):
my @data = (Some existing values); my @column = <Read 125 values from some file>; for my $index(@columns){ .. use $data[$index] }
Hopefully, this will help you formulate your question more coherently.

            "XML is like violence: if it doesn't solve your problem, use more."

Replies are listed 'Best First'.
Re^2: How to store the indexes of a array
by anonym (Acolyte) on Oct 14, 2011 at 17:09 UTC

    For instance, my code is :

    my $infile = $ARGV[0]; open (IFILE, "<", $infile) || die "Cannot open : $!\n"; ## read the input file my @data; my $COLUMNTOPARSE; my $local; while (<IFILE>) { chomp; my @local = split ('\t',$_); $COLUMNTOPARSE = $local[$ARGV[1]]; push @data; $COLUMNTOPARSE; } close IFILE; my $count = @data;

    Now I wanted to get a generalization of all the indices of 125 elements stored in the $COLUMNTOPARSE in order to calculate variance of those elements

    my $variance; my $var; foreach my $data[$index] (@data) { $var = 1/($count-1); $variance = $var*(($data[$index]-$Average)**2); } print "$variance\n";

    But this $data$index way does not work.How should I proceed? Thanks..

      It doesn't sound to me like you want the indices of the array, but the actual values. When you use foreach (or for) with a scalar followed by an array, that's what you get. So you can just go ahead and use the values in your formula:

      foreach my $value (@data) { $var = 1/($count-1); $variance = $var*(($value-$Average)**2); }

      If you actually need the indices, you can use a C-style for loop or the range operator, in both cases letting the scalar value of the array represent the number of elements in it:

      for( my $i=0; $i < @data; $i++ ){ # do something with $data[$i] } # or for my $i (0..(@data-1)){ # do something with $data[$i] }

        Hey, Thanks for the reply.I was actually confused if that way was right.In either of the three cases you have shown, it gives the same values. Thanks..