Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Length of array in hash of arrays

by ambrus (Abbot)
on May 09, 2013 at 13:57 UTC ( #1032776=obfuscated: print w/replies, xml ) Need Help??


I have a hash of arrays like this:

my %g = ( k => [8, 2, 10, 2, 1, 3], l => [10, 7, 9, 0, 1] );
I know I can access the first element in one of the arrays like $g{k}[0]. But how do I get the length of that array?


Just try using random sigils, some combination is bound to work. The following script eases this task: it quickly runs all combinations of random sigils and prints the code that gives the right answer.

use 5.014; no warnings; # some non-sensical combination of sigils would give warn +ings use strict; # we want answers without symbolic references my %g = ( k => [8, 2, 10, 2, 1, 3], l => [10, 7, 9, 0, 1] ); sub sigil_combination { sprintf("%X", $_[0]) =~ y/0-9A-F/$@#%*~^\->(){}.,;/r; } for my $n0 (1..1e5) { my $c = "length " . sigil_combination($n0) . "g{k}"; if (6 == eval $c) { say "$c"; } } __END__

This prints the following standard solution using the array length operator $#:

length ~$~#g{k}
and if you're lucky, it may print the following tricky solutions as a bonus too:
length {}%$g{k} length {}%@g{k} length {}-$g{k} length {}-@g{k}

Replies are listed 'Best First'.
Re: Length of array in hash of arrays
by Grimy (Pilgrim) on May 12, 2013 at 08:43 UTC
    You're aware that none of these solutions actually print the length of the array, right? Well, they do so in this example, but by pure serendipity. The actual “standard” way to get the length of the array would be $#{$g{k}} or 0+@{$g{k}}

      Yes, I'm aware of that. That's why this is post is in Obfuscated Code rather than Meditations. If you want to get the real solution, the simpler

      use 5.012; no warnings; my @t = map { rand } 1..60; my %g = (k => \@t) +; for my $n (0..1e3) { (my $s = $n) =~ y/0-9/ {}@#$%=^~+/; my $c= qq( +${s}g{k}}); if (60 == eval $c) { warn $c; } }
      prints it together with another fake solution.

        The simplest way must contain the function 'length':

      Like this:
      $ perl -e 'my %g = (k => [8, 2, 10, 2, 1, 3],l => [10, 7, 9, 0, 1]); f +oreach $keyval(sort keys %g){print 0+@{$g{$keyval}};}'

        That prints only the length of the first subarray, the one corresponding to the key "k". Let's do better and use the each keyword to print the length of each subarray.

        my %g = (k => [8, 2, 10, 2, 1, 3],l => [10, 7, 9, 0, 1]); %gkey = sort keys %g; print 0+@{$g{each %gkey}}, "\n";

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: obfuscated [id://1032776]
Front-paged by Corion
[Discipulus]: ah thanks.. 1nickt all is well with the new job?

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2018-01-19 18:05 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (222 votes). Check out past polls.