LucaPette has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks,

Reading Perl documentation i learned that the chomp function chomps the hash's values, but not its keys.
Obviously that's right but i have used a snippet like the following to build an hash from a file:

chomp (my %an_hash=<A_File>);

And also in this case it chomps only the values.
To obtain an hash from a file with keys and values both chomped i have used a chunk of code like this:

my %an_hash; while (<A_FILE>) { chomp; chomp(my $tmpvalue=<A_FILE>); $an_hash{$_}=$tmpvalue; }
It works but it seems too much complicated, the former snippet don't work fine but it's really short and simple.
Can someone suggest to me a simpler (or shorter) solution?

Replies are listed 'Best First'.
Re: Building a chomped hash from a file
by sauoq (Abbot) on Oct 28, 2005 at 19:35 UTC
    my %hash = map {chomp; $_} <FILE>
    -sauoq
    "My two cents aren't worth a dime.";
    
Re: Building a chomped hash from a file
by Errto (Vicar) on Oct 28, 2005 at 19:17 UTC

    Well, it is possible to achieve what you want with a one-liner like so:

    my %hash = do { chomp(my @lines = <FILE>); @lines };
    Also note that there's a very important difference between your proposed code and the actual code. The proposed code reads in the entire file at once into a list in memory (which is also what my code does), whereas the second snippet reads two lines at a time. So it's not just a matter of code aesthetics - it's a matter of what you want your program to do.

    The reason your proposed snippet doesn't work is that you can't alter the keys in a hash - it really goes against the concept of what a hash is. You can alter the value for a given key, and you can add and delete keys, but it doesn't really make sense to alter a key.

Re: Building a chomped hash from a file
by Anonymous Monk on Oct 28, 2005 at 22:12 UTC

      While I like this, I think it is more obfuscated than I'd like to see in serious code. I'd even prefer 1+chomp to [chomp]. Even so, it's an unexpected use of grep and I'd probably avoid it.

      -sauoq
      "My two cents aren't worth a dime.";