What's the Perl equivalent of Python's enumerate?
You can use map
, like this
my @data = qw / a b c /;
my @enumeration = map [ $_, $data[$_] ], 0 .. $#data;
enumerate
returns an iterator, not a list, so you should really be asking for an iterator.
In Perl 5.12.0 and up, you can use each
to iterate over arrays:
use strict;
use warnings 'all';
use 5.012;
my @a = qw(foo bar baz);
while (my ($i, $v) = each @a) {
say "$i -> $v";
}
__END__
0 -> foo
1 -> bar
2 -> baz
However, you should be very careful when using each
; some people even discourage its use altogether.
Perl doesn't have a built-in function to do that but it's easy to roll your own.
Using map
:
my @a = qw(a b c);
my $i = 0;
my @b = map [$i++, $_], @a; # ([0, 'a'], [1, 'b'], [2, 'c'])
As of v5.20, Perl's new slice syntax does something similar:
my @a = qw(a b c);
my @b = %a[0..$#a]; # (0, 'a', 1, 'b', 2, 'c')
That slice syntax returns a list of index/value pairs but it's a flat list. The pairs aren't grouped into nested arrays. If that's important to your application you can use the pairmap function from List::Util to do it:
use List::Util qw(pairmap);
my @a = qw(a b c);
my @b = pairmap {[$a, $b]} %a[0..$#a]; # ([0, 'a'], [1, 'b'], [2, 'c'])