[Chicago-talk] Deprecated use of hash as a reference

Steven Lembark lembark at wrkhors.com
Thu Apr 8 16:30:20 PDT 2010


On Thu, 8 Apr 2010 14:32:18 -0500
Joel Limardo <joel.limardo at forwardphase.com> wrote:

> Can someone publish more of this code...I tried to emulate this by guessing
> and came up with this:
> 
> -- snip --
> 
> #!/usr/bin/perl -w
> use strict;
> use Data::Dumper;
> 
> my %hash = ();
> my @junk = qw|a b c d e f g|;
> 
> for(@junk)
> {
>     push @{{\%hash}->{'something'}},{id=>$_};
> }
> print Dumper %hash;
> 
> -- end snip --

Think of it this way:

    Hashes store scalars as values.

    The scalar values are accessed individually
    via "$hash{ $key }". 

    If the scalar value is a reference it can be
    de-referenced at the time of extraction.

You could do:

    my $array_ref   = $hash{ $key };

    push @$array_ref, $value;

but can also do:

    push @{ $hash{ $key } }, $value;

and save an extraneous assignment.

Net result: Don't turn a hash into a hashref to
dereference it locally; use it as a hash and get
the value.

Example: given the logfile from hell you want to
regex all of the initial words and assemble a list
of like-minded messages.

The regex can be whatever you like, for this 
example I'll use the first set of word char's
on the line. Other likely options would be 
splitting it on whitespace or indexng the first
colon for a substr.

    my $regex   = qr/^ (\w+) /x;  

    my %hash    = ();

    while( <$fh> )
    {
        my ( $key ) = /$regex/o;

        push @{ $hash{ $key } }, $_;
    }

    # at this point %hash is keyed by 
    # the first word char's with values
    # of arrayref's containing the ordered
    # messages.

If you wanted to sort the lists for easier
handling you could do something like:

    @$_ = sort @$_ for values %hash;

If you wanted to walk down the "Frobnicate"
messages looking for other information you
could:

    for my $msg ( @{ $hash{ Frobnicate } } )
    {
        # $msg begins with Frobnicate, has
        # whatever else on it you wanted to know.
        # ...
    }




-- 
Steven Lembark                                            85-09 90th St.
Workhorse Computing                                 Woodhaven, NY, 11421
lembark at wrkhors.com                                      +1 888 359 3508


More information about the Chicago-talk mailing list