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 (Chancellor) 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 ] );