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.