[Israel.pm] Another newbie question - Hashes
Gaal Yahas
gaal at forum2.org
Thu Feb 5 03:50:52 PST 2004
On Thu, Feb 05, 2004 at 11:40:24AM +0000, Mikhael Goikhman wrote:
> On 05 Feb 2004 13:16:11 +0200, Gaal Yahas wrote:
> >
> > If you're going for code that's easy for a beginner to grasp, this is
> > much clearer:
> >
> > while (<FILE>) {
> > my($key, $value) = split /\s+/, $_, 2;
> > $hash{$key} = $value;
> > }
>
> Gaal, Yuval Yaari already mentioned a bug in this code.
> I noticed this bug too when you posted, but didn't want to interfere. :)
>
> <> returns a line (or lines in list context) with trailing "\n" in them.
> So, $value ends up with "\n" in it.
>
> To fix this, one solution is to add chomp. Another solution is to remove
> the third argument from split (but you can't remove it in your original
> code that converts array to hash, you should use chomp there):
>
> my ($key, $value) = split /\s+/, $_;
>
> Some sane file format checks should be added too to avoid other bugs.
I stand bug corrected!
And yet my points remain:
- $/ and a temporary var are better not used here, for several reasons.
- while() is more straightforward and more extensible, and certainly
clearer for a beginner. The "sane file format checks" were what I was
talking about.
--
Gaal Yahas <gaal at forum2.org>
http://gaal.livejournal.com/
More information about the Perl
mailing list