http://www.perlmonks.org?node_id=928497


in reply to hash_reference from file

#!/usr/bin/perl use Data::Dumper; use constant KEYS => qw/APP REG KPI INTERFACE DATE TIME NODE RAN SUCC_RATE/; use warnings; use strict; my @array; while (<DATA>) { my @line = split; my %hash; @hash{+KEYS} = @line; push @array, {%hash}; } print Dumper \@array; __DATA__ CORDR KZN MTC-N AINT 2011-09-29 09:00 DTL PM05 83.79 4 - - CORDR SGC MTC-N AINT 2011-09-29 09:00 JSA BR20 85.39 3 - - CORDR SGC MTC-N AINT 2011-09-29 09:00 JSA BR21 86.06 1 - - CORDR Unk MTC-N AINT 2011-09-29 09:00 JSA BR22 84.55 2 - - CORDR SGC MTC-N AINT 2011-09-29 09:00 JSA RN10 86.97 1 - - CORDR SGC MTC-N AINT 2011-09-29 09:00 JSA RS11 84.57 2 - - CORDR SGC MTC-N AINT 2011-09-29 09:00 JSA RS12 86.31 2 - - CORDR SGC MTC-N AINT 2011-09-29 09:00 JSA SD10 86.79 1 - - CORDR SGC MTC-N AINT 2011-09-29 09:00 JSA SN10 85.54 1 - -
To understand, read the following:
The strictures, according to Seuss
Data::Dumper
constant
perldata

Replies are listed 'Best First'.
Re^2: hash_reference from file
by jwkrahn (Abbot) on Sep 29, 2011 at 11:33 UTC
    while (<DATA>) { my @line = split; my %hash; @hash{+KEYS} = @line; push @array, {%hash}; }

    Why create a hash in the lexical scope of the while loop and then make a copy of that hash instead of just using a reference to that lexically scoped hash?

    while (<DATA>) { my %hash; @hash{ +KEYS } = split; push @array, \%hash; }
      You are absolutely right. I was typing too fast :)
Re^2: hash_reference from file
by hmadhi (Acolyte) on Sep 29, 2011 at 09:32 UTC

    Cool. Just what the Doctor Ordered.

Re^2: hash_reference from file
by hmadhi (Acolyte) on Sep 29, 2011 at 10:54 UTC

    Next Question: How do I exclude certain lines. eg exclude lines that have 'Unk'

      Just don't push if $hash{REG} eq 'Unk'...

        Thanks