in reply to keep track of array indexes

You don't say what you are really trying to do, but would you not be better served with a hash (aka "associative array")?

#!/usr/bin/perl use strict; use warnings; my %bits = ( 4 => 'string', 1 => 'this', 3 => 'my', 2 => 'is', ); print join ' ', map $bits{ $_ }, 1 .. 4;
Output:
this is my string

The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^2: keep track of array indexes
by AnomalousMonk (Archbishop) on Jan 02, 2016 at 19:24 UTC

    Or, slightly differently:

    c:\@Work\Perl>perl -wMstrict -le "my @words = qw/this a sentence is/; my %dict = map { $_ => $words[$_] } 0 .. $#words; ;; my @order = (0, 3, 1, 2); print join ' ', map $dict{$_}, @order; " this is a sentence


    Give a man a fish:  <%-{-{-{-<

      thanks.. interesting method. But the ultimate question is, if the order of @words is randomized, how would i re-order @order so that it still produces "this is a sentence" ? pseudo code:
      @words = "this is my sentence" @order = 0, 3, 1, 2 print @order randomize(@words) @order = 2,1,0,3 randomize(@words) @order = 1,0,3,2
      the code is somehow keeping track of changes in the @words array and updating the @order array.
        The answer is the same: Use a hash.
        #!/usr/bin/perl use warnings; use strict; use feature qw{ say }; use List::Util qw{ shuffle }; my @words = qw( this is my string ); my @order = 0 .. $#words; my %ord; @ord{@words} = 0 .. $#words; @words = shuffle(@words); @order = @ord{@words}; print do { local $" = "\t"; "@words\n", "@order\n" }; say join ' ', map $words[$_], sort { $order[$a] <=> $order[$b] } @order;
        ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
Re^2: keep track of array indexes
by Anonymous Monk on Jan 02, 2016 at 18:09 UTC
    hmm yes, hash seems a better idea :) thanks, that totally skipped my mind