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

I have a data structure:
{ A [ [0] 0.298024546928301, [1] 0.310437805395979, [2] 0.362849758185986, [3] 0.300927220244308, [4] 0.30014286502788 ], C [ [0] 0.200608102102475, [1] 0.274657378132592, [2] 0.192625882771276, [3] 0.162815453143259, [4] 0.158490613195079 ], G [ [0] 0.217826947179901, [1] 0.132847137086947, [2] 0.206439273801657, [3] 0.188858010150455, [4] 0.253229183805833 ], T [ [0] 0.28354040378812, [1] 0.282057679385473, [2] 0.238085085241806, [3] 0.347398866718639, [4] 0.288136438478111 ] }

And I want to access all of the main values at once, and possibly store them in separate arrays, for example:

$arrayA = (0.298024546928301, 0.310437805395979, 0.362849758185986, 0.300927220244308, 0.30014286502788)

For the values attached to the 'A' key. I can do this either by iterating over the hash and pushing each value into an array or via:

$test{'A'}[0,1,2,3];

However the number of values is variable and i'd rather not have to specify 0,1,2,3,4,5 etc. but rather just a range based on a variable. However when I do:

$test{'A'}[0..$value];

or:

$test{'A'}[0..3];

It no longer works. Why is that and how can I accomplish this?

Replies are listed 'Best First'.
Re: Extract hash values without a loop
by huck (Prior) on Oct 06, 2017 at 19:23 UTC

    my @arrayA = @{$test{'A'}};

Re: Extract hash values without a loop
by AnomalousMonk (Archbishop) on Oct 06, 2017 at 19:32 UTC

    Some more examples:

    c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my %test = ( 'A' => [ qw(foo one fee three four bar) ], 'T' => [ 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3 ], ); ;; dd \%test; ;; my $value = 3; my @ra = @{ $test{A} }[ 0 .. $value ]; dd \@ra; ;; my @rb = @{ $test{T} }[ reverse 1 .. 4 ]; dd \@rb; " { A => ["foo", "one", "fee", "three", "four", "bar"], T => ["0.9", "0.8", "0.7", "0.6", "0.5", "0.4", "0.3"], } ["foo", "one", "fee", "three"] ["0.5", "0.6", "0.7", "0.8"]

    Update: See perlref, perlreftut, perldsc. (Update: In perldsc, see especially COMMON MISTAKES.)


    Give a man a fish:  <%-{-{-{-<

Re: Extract hash values without a loop
by Anonymous Monk on Oct 06, 2017 at 19:26 UTC
    @{$test{A}}[0..3]