2

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] ?

4
  • 1
    And to answer my own question.. @subarray=@const_arr[eval($str)] Commented Jan 23, 2012 at 16:52
  • 1
    Using eval to parse your input is overkill, and opens the door to security issues. split is a better tool for the job. Commented Jan 23, 2012 at 17:17
  • Thanks Eric and Choroba, this was what I was looking for. Commented Jan 23, 2012 at 17:55
  • my @const_arr= ( a,b,c,d,e,f ) ; Commented Jan 23, 2012 at 18:26

4 Answers 4

5

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";
Sign up to request clarification or add additional context in comments.

3 Comments

This answer would be better if it kept the 'my's and variable names from the question.
@hochgurgler: Well, I cannot use the name "const" for something that is not a constant :-)
@choroba, One could argue that using the name "@const_arr" makes it a constant. (Just not one enforced by the compiler.)
4

An array slice will do this:

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

1 Comment

This answer doesn't address the issue of how to get from the string "1,4" to the list (1,4)
4
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];

Comments

3

@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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.