Search code examples
perlperl-data-structures

building a hash from a string


I have the below string on perl :

my $string = xyz;1;xyz;2;a;2;b;2 

i want to build a hash after for this string like below :

my @array =split /;/,$string;

$hash{xyz} =(1,2);
$hash{b}=(2);
$hahs{a}=(2);

what is the perl way to do this?


Solution

  • my $string = "xyz;1;xyz;2;a;2;b;2";
    my %hash;
    push @{$hash{$1}}, $2 while $string =~ s/^(\w+);(\d+);?//g;
    

    Actually

    push @{$hash{$1}}, $2 while $string =~ m/(\w+);(\d+);?/g;
    

    would be better, since that doesn't eat up your original string.