Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re^3: novice with hash/data file question

by leonidlm (Pilgrim)
on Sep 02, 2008 at 11:39 UTC ( [id://708454]=note: print w/replies, xml ) Need Help??


in reply to Re^2: novice with hash/data file question
in thread noob with hash/data file question

Use this code:
open(FILE, '<', 'data.txt'); my %result = map {split /\|/; ($_[0] => $_[1])} <FILE>; close(FILE);
It will fulfill all your needs :)

Replies are listed 'Best First'.
Re^4: novice with hash/data file question
by johngg (Canon) on Sep 02, 2008 at 14:12 UTC
    As well as the issues with the success of the open and with chomp already pointed out by jwkrahn, you should note that the ($_[0] => $_[1]) is superfluous and could be omitted to get the same result.

    my %result = map {split /\|/} <FILE>;

    Using a lexical filehandle inside the scope of a do would save an explicit close.

    use strict; use warnings; use Data::Dumper; my $inFile = q{spw708412.dat}; my %stuff = do { open my $inFH, q{<}, $inFile or die qq{open: < $inFile: $!\n}; map { chomp; split m{\|} } <$inFH>; }; print Data::Dumper->Dumpxs( [ \ %stuff ], [ q{*stuff} ] );

    Running it.

    [johngg@ovs276 perl]$ cat spw708412.dat abc|123 def|456 [johngg@ovs276 perl]$ ./spw708412 %stuff = ( 'def' => '456', 'abc' => '123' ); [johngg@ovs276 perl]$

    I hope this is of interest.

    Cheers,

    JohnGG

Re^4: novice with hash/data file question
by jwkrahn (Abbot) on Sep 02, 2008 at 12:51 UTC

    Except that it doesn't verify that the file opened so the filehandle could be invalid and it doesn't chomp so there could be trailing newlines.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (2)
As of 2026-04-14 13:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.