Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Create a hash whose keys and values come from a given array

by clueless newbie (Deacon)
on Sep 06, 2017 at 09:42 UTC ( #1198760=note: print w/replies, xml ) Need Help??


in reply to Create a hash whose keys and values come from a given array

Using autobox

use autobox::universal qw(type); use Data::Dumper; use strict; use warnings; my @array = ('a', 1, 2, 3, 4, 'b', 6, 7, 8); my %hash = (); my $key; for (@array) { if (type($_) eq 'STRING') { $key=$_; } else { push @{$hash{$key}},$_; } } warn Data::Dumper->Dump([\%hash],[qw(*hash)]),' ';

Replies are listed 'Best First'.
Re^2: Create a hash whose keys and values come from a given array
by afoken (Canon) on Sep 06, 2017 at 20:09 UTC

    Nice. But I would just use /\D/ to detect a non-numeric array element. No need to mess with automatically-generated classes:

    # no "use autobox::universal" # ... for (@array) { if (/\D/) { $key=$_; } else { push @{$hash{$key}},$_; } } # ...

    Alternatively, use looks_like_number() from Scalar::Util that wraps the Perl API function of the same name:

    # ... use Scalar::Util qw( looks_like_number ); # ... for (@array) { if (looks_like_number($_)) { $key=$_; } else { push @{$hash{$key}},$_; } } # ...

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
      Autobox and \D play differently:
      use autobox::universal qw(type); use Data::Dumper; use strict; use warnings; my @array = ('a', 1, 2, 3, 4, 'b', 6, 7, 8, '1', 2, 3, 4, 5); # note t +he '1' which autobox will call a string. my %hash = (); my $key; for (@array) { if (type($_) eq 'STRING') { $key=$_; } else { push @{$hash{$key}},$_; } } warn Data::Dumper->Dump([\%hash],[qw(*hash)]),' ';
      The output from Data::Dumper:
      %hash = ( '1' => [ 2, 3, 4, 5 ], 'b' => [ 6, 7, 8 ], 'a' => [ 1, 2, 3, 4 ] );

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2019-11-12 06:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Strict and warnings: which comes first?



    Results (64 votes). Check out past polls.

    Notices?