[Israel.pm] Another newbie question - Hashes

Gaal Yahas gaal at forum2.org
Thu Feb 5 02:39:44 PST 2004


Did you try it?

<> in list context returns a list of lines, so you don't need to split
by newline.

On Thu, Feb 05, 2004 at 11:13:37AM +0200, Yuval Yaari wrote:
> 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
> >
> > 
> >
> 
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://www.perl.org.il/mailman/listinfo/perl
> 
> YAPC::Israel::2004
> http://www.perl.org.il/YAPC/2004/

-- 
Gaal Yahas <gaal at forum2.org>
http://gaal.livejournal.com/



More information about the Perl mailing list