Noam Kremen
Noam Kremen

Reputation: 418

Perl: How to simultaneously access mutliple nonconsecutive elements in an array?

The array I want to query does not change during execution:

my @const_arr=qw( a b c d e f g);

The input is a string containing the indices I want to access, for example:

my $str ="1,4";

Is there something (besides iterating over the indices in $str) along the lines of @subarray = @const_arr[$str] that will result in @subarray containing [b,e] ?

Upvotes: 2

Views: 307

Answers (4)

Eric Strom
Eric Strom

Reputation: 40142

my @const_arr = qw(a b c d e f);  # the {...} creates a hash reference, 
                                  # not what you wanted

my $str = "1,4";

my @idx = split /,/ => $str;

my @wanted = @const_arr[@idx];

or in one line:

my @wanted = @const_arr[split /,/ => $str];

Upvotes: 4

choroba
choroba

Reputation: 241858

If the indices are in a string, you can split the string to get them:

@array    = qw(a b c d e);
$indices  = '1,4';
@subarray = @array[split /,/, $indices];
print "@subarray\n";

Upvotes: 5

JRFerguson
JRFerguson

Reputation: 7516

An array slice will do this:

@const_arr=qw(a b c d e);
@subarray=(@const_arr)[1,4];
print "@subarray"'

Upvotes: 4

Taras
Taras

Reputation: 920

@const_arr should initiate like this:

my @const_arr = qw(a b c d e f);

then you can access to 1 and 4 element by:

@const_arr[1,4]

Upvotes: 3

Related Questions