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

Firstly, you're brilliant....

And the first line was part of something i copied from a different script i made a long time ago

(apparently a year lull in practice makes what little knowledge I already had go away).

I had tried to do this a lot of different ways and finally resorted to savaging form previous scripts in hopes of figuring it out, if only by mistake.

Now that i see the answer written down, it makes sense.

But yes, you were absolutely correct. I've been googling everything I could find on hashes in perl for hours. Maybe my key words correct, but I couldn't find anything on accessing data from a file through a hash. Thanks a lot.
  • Comment on Re^2: novice with hash/data file question

Replies are listed 'Best First'.
Re^3: novice with hash/data file question
by leonidlm (Pilgrim) on Sep 02, 2008 at 11:39 UTC
    Use this code:
    open(FILE, '<', 'data.txt'); my %result = map {split /\|/; ($_[0] => $_[1])} <FILE>; close(FILE);
    It will fulfill all your needs :)
      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

      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.

Re^3: novice with hash/data file question
by llancet (Friar) on Sep 02, 2008 at 10:52 UTC
    What you need is to firstly read a textbook about perl carefully...