Creating a hash string => list of lists, what am I doing wrong?

In perl, I am trying to create a hash of a list of lists. It looks something like this:

my %entries;
while(<>)
{
    if(/complicated regex ommitted/)
    {
        my @entry = ($2, $3, $4);
        if(exists $entries{$1})
        {
            push @{$entries{$1}}, @entry;
        }
        else
        {
            $entries{$1} = @entry;
        }
}

As a result of the hash, there are all the keys that I expect, but the value of the "list of lists" is not created correctly. What am I doing wrong?

Change . Maybe something is wrong with how I try to access the resulting hash. Here is the code

foreach $key (keys %entries)
{
    my $size = {@entries{$key}};
    # just says "HASH(0xaddress)"?
    print "$key: $size\n"; 
    foreach(@{entries{$key}})
    {
        # loop just goes through once, prints out just " : "
        print "\t$_[0]: $_[1] $_[2]\n";
    }
}   
+3
source share
4 answers

Perl has an auto-activation feature that lets you create spring forests when you need it. This simplifies your code:

my %entries;
while(<>)
{
    if (/complicated regex ommitted/)
    {
        my($key,@entry) = ($1, $2, $3, $4);
        push @{ $entries{$key} }, \@entry;
    }
}

There is no need to check if this is the first group of records for a given key.

To dump content %entries, use code similar to

foreach my $key (sort keys %entries)
{
    my $n = @{ $entries{$key} };
    print "$key ($n):\n";

    foreach my $l (@{ $entries{$key} })
    {
        print "\t$l->[0]: $l->[1] $l->[2]\n";
    }
}
+4

, listref. :

push @{$entries{$1}}, \@entry;

( . , , .)

+4

You need to click the link to the list, otherwise the lists will simply be added to get a simple list (see the manual for push). A "list of list" is always a "list of list links" in Perl.

0
source
while ( <> ) {

if ( / (r) (e) (g) (e) x /x ) {
    push @{ $entry{ $1 } }, [ $2, $3, $4 ];
}
}

or in 1 line:

/(r)(e)(g)(e)x/ and push @{$entry{$1}}, [$2, $3, $4] while <>;

and show them:

use Data::Dumper;

print Dumper \%entry;
0
source

Source: https://habr.com/ru/post/1752120/


All Articles