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

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". ;-)

Replies are listed 'Best First'.
Re^3: Create a hash whose keys and values come from a given array
by clueless newbie (Curate) on Sep 07, 2017 at 11:19 UTC
    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 ] );