[Israel.pm] Another newbie question - Hashes

Yuval Yaari yuval at windax.com
Thu Feb 5 01:13:37 PST 2004


Gaal,

I don't use it because this code doesn't work (think about them poor 
\n's that don't get split()) :)
Hacking up the code a little would result:

## Perl code starts here... ##
open(FILE, "<file") or die("Couldn't open the file: $!");
my %hash = map { split(/\s+/, $_, 2) } split (/\n/, do{ local $/; <FILE> });
close(FILE) or die("Couldn't close the file: $!");
## ...And ends here... ##

But this is a bit more hackish, I would leave tons of comments before 
such code, or at least break it to several lines.


  --Yuval


Gaal Yahas wrote:

>On Tue, Feb 03, 2004 at 05:40:18PM +0200, Yuval Yaari wrote:
>  
>
>>I tried making my example as basic as possible (a simple question 
>>deserves a simple answer).
>>Anyway, here's what I do in real life (as always TMTOWTDI):
>>
>>### BEGIN ###
>>open(FILE, "<file");
>>my $file = do{ local $/; <FILE> };
>>close(FILE);
>>my %hash = map { split(/\s+/, $_, 2) } split (/\n/, $file);
>>### END ###
>>    
>>
>
>Well, if you're already willing to read the whole file to memory why
>don't you just use <> in list context:
>
>    open my $fh, "filename" or die "$0:open:$!";
>    my %hash = map { split(/\s+/, $_, 2) } <$fh>;
>    close $fh or die "$0:close:$!";      # or simply let $fh go out of scope
>
>  
>




More information about the Perl mailing list