Home > Enterprise >  Is there any function in Perl that shifts the array element without removing them?
Is there any function in Perl that shifts the array element without removing them?

Time:03-02

I have an array, say @array1 = qw(abc def ghi jkl).

Now, I want to use this array in a way that elements are shifted 1 by 1, but that shifting takes place virtually, and not in the array.

Like, "shift" will shift the elements and remove them from the array. But, I don't want those elements to be removed.

Short Code Snippet:

while (my $rName = shift @array1) { 
    my $bName = shift @array1 ; 
    ## Do something now with the value 
}
##And now, I want that I can use @array1 again with the original elements residing

How can it be implemented?

CodePudding user response:

Use a C-style for loop and increment by two. $#foo is the index of the last element.

my @foo = 0 .. 5;
for (my $i = 0; $i <= $#foo; $i  = 2){
    my $r_name = $foo[$i];
    my $b_name = $foo[$i 1];
}

If you wanted fancier-looking code, you could use natatime from List::MoreUtils on CPAN, which gives you an iterator that you can use in a while loop.

use List::MoreUtils 'natatime';

my @foo = 0 .. 5;
my $it = natatime 2, @foo;
while ( my ($r_name, $b_name) = $it->() ) {
    print "$r_name $b_name\n";
}

CodePudding user response:

You can also use pairs from the core List::Util module:

A convenient shortcut to operating on even-sized lists of pairs, this function returns a list of ARRAY references, each containing two items from the given list.

#!/usr/bin/env perl                                                                                                                                                                                                                               
use strict;
use warnings;
use feature qw/say/;
use List::Util qw/pairs/;

my @array1 = qw/a 1 b 2 c 3/;
for my $pair (pairs @array1) {
    my ($rName, $bName) = @$pair;
    say "$rName => $bName";
}
say "@array1";
  • Related