[Israel.pm] Another newbie question - Hashes

Mikhael Goikhman migo at homemail.com
Thu Feb 5 03:40:24 PST 2004

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.


perl -e 'print+chr(64+hex)for+split//,d9b815c07f9b8d1e'

More information about the Perl mailing list