Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Make a hash by a range of keys and values

by johngg (Canon)
on Nov 01, 2018 at 00:27 UTC ( [id://1225027]=note: print w/replies, xml ) Need Help??


in reply to Make a hash by a range of keys and values

This is similar to already proposed solutions except that it uses maps rather than loops. I'm only posting it because others might be interested in the way you can pass a subroutine reference to Data::Dumper->Sortkeys() to control the key sort order; I'd not seen this before but went looking in the docs for a solution when I realised that magic-incrementing the key beyond "z" would make a mess of the default ->Sortkeys() output.

use 5.026; use warnings; use Data::Dumper; my $numX = 5; my $numY = 7; my $key = q{a}; my %posns = map { my $y = $_; map { my $x = $_; $key ++ => [ $x, $y ] } 0 .. $numX - 1 ; } 0 .. $numY - 1; my $rcKeySorter = sub { my $rhPosns = shift; my @sortOrder = map { unpack q{x4a*}, $_ } sort map { pack q{Na*}, length, $_ } keys %{ $rhPosns }; return \ @sortOrder; }; print Data::Dumper ->new( [ \ %posns ], [ qw{ *posns } ] ) ->Sortkeys( $rcKeySorter ) ->Dumpxs();

The output.

%posns = ( 'a' => [ 0, 0 ], 'b' => [ 1, 0 ], 'c' => [ 2, 0 ], 'd' => [ 3, 0 ], 'e' => [ 4, 0 ], 'f' => [ 0, 1 ], 'g' => [ 1, 1 ], 'h' => [ 2, 1 ], 'i' => [ 3, 1 ], 'j' => [ 4, 1 ], 'k' => [ 0, 2 ], 'l' => [ 1, 2 ], 'm' => [ 2, 2 ], 'n' => [ 3, 2 ], 'o' => [ 4, 2 ], 'p' => [ 0, 3 ], 'q' => [ 1, 3 ], 'r' => [ 2, 3 ], 's' => [ 3, 3 ], 't' => [ 4, 3 ], 'u' => [ 0, 4 ], 'v' => [ 1, 4 ], 'w' => [ 2, 4 ], 'x' => [ 3, 4 ], 'y' => [ 4, 4 ], 'z' => [ 0, 5 ], 'aa' => [ 1, 5 ], 'ab' => [ 2, 5 ], 'ac' => [ 3, 5 ], 'ad' => [ 4, 5 ], 'ae' => [ 0, 6 ], 'af' => [ 1, 6 ], 'ag' => [ 2, 6 ], 'ah' => [ 3, 6 ], 'ai' => [ 4, 6 ] );

I hope this is of interest.

Cheers,

JohnGG

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1225027]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (1)
As of 2024-04-25 00:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found