Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Loading an anonymous hash

by friedo (Prior)
on Mar 19, 2008 at 14:47 UTC ( [id://675011]=note: print w/replies, xml ) Need Help??


in reply to Loading an anonymous hash

What you've got there is an array reference with a hash reference as its only element. To make an anonymous hash reference, you just use curlies ({}). Since you want to read in multiple comma-delimited rows, you probably want an array of hash references, one hashref for each row.

my @records; # store the hashrefs in here my @keys = qw(Emp_No Emp_Lname Emp_Fname Emp_SSN Emp_DOB Emp_aka); open(IN,"input.txt") or die("Can't open input.txt"); while(<IN>) { chomp; my %Employee_Rec; @Employee_Rec{@keys} = split /,/, $_; # hash slice print "$Employee_Rec{Emp_No} \n"; print "$Employee_Rec{Emp_Lname} \n"; print "$Employee_Rec{Emp_Fname} \n"; print "$Employee_Rec{Emp_SSN} \n"; print "$Employee_Rec{Emp_DOB} \n"; print "$Employee_Rec{Emp_aka} \n"; push @records, \%Employee_Rec; } close(IN);

To inspect @records and make sure you've built it correctly, you can use Data::Dumper.

Replies are listed 'Best First'.
Re^2: Loading an anonymous hash
by why_bird (Pilgrim) on Mar 19, 2008 at 15:27 UTC

    Nicely done. I remember trying to do something like this a while back and struggling for a long time because my hash was not properly localised. You have to make sure that my %Employee_Rec is my'd inside that while loop otherwise it will no longer be anonymous and all you'll get is an array full of references to the same hash---the last one you entered...

    ........
    Those are my principles. If you don't like them I have others.
    -- Groucho Marx
    .......

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://675011]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (7)
As of 2024-04-23 13:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found