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

I wonder if there is a more elegant shorter way for doing some common array manipulation tasks:

  • swap two elements of an array
  • # swap $index1 and $index2 of @array $temp=$array[$index2]; $array[$index2]=$array[$index1]; $array[$index1]=$temp;
  • step $index in direction $dir (+1 or -1) in array in a 'circular' way:
  • # step $index in $dir direction in @array circular $index+=$dir; $index=0 if $index>=@array; $index=@array-1 if $index<0;

    Replies are listed 'Best First'.
    Re: Array manipulation how to
    by moritz (Cardinal) on Feb 07, 2012 at 08:53 UTC
        What kind of sytax is this: @array[$index1,$index2]? What does this exactly mean?
    Re: Array manipulation how to
    by Ratazong (Monsignor) on Feb 07, 2012 at 08:54 UTC
      Hi!

      for 1., be inspired by the following code:

      my $x = 5; my $y = 2; ($x, $y) = ($y, $x); print ("$x $y\n");
      for 2., check here in the FAQ on how to handle circular lists

      HTH, Rata
    Re: Array manipulation how to
    by chessgui (Scribe) on Feb 07, 2012 at 11:21 UTC
      Let me add one more:

    • rotate an array left/right
    • # rotate @array left my $temp=shift @array; push(@array,$temp); # rotate @array right my $temp=pop @array; unshift(@array,$temp);
        And without an additional variable:
        push @a, shift @a; unshift @a, pop @a;
          would this work?
          @_=@a; push, shift; @_=@a; unshift, pop;
    Re: Array manipulation how to
    by Anonymous Monk on Feb 07, 2012 at 12:36 UTC
      Beware low-flying golf balls...