Re: chomp hash keys?



usenet@xxxxxxxxxxxxxxx schreef:

#!/usr/bin/perl
use strict; use warnings;
use Data::Dumper;

chomp (my %person = (<DATA>));
print Dumper \%person;

__DATA__
name
fred
occupation
quarryman
friend
barney

The keys, of course, have linefeeds on the end, which I do not want.
What is the best way to populate my hash with linefeed-ed data? Must
I build a 2-at-a-time loop and populate one pair per iteration? That
seems like a crummy solution!

Good question this, and I like the answers too:

my %person = grep [ chomp ], <DATA>; (John W. Krahn)

my %person = map {chomp; $_} <DATA>; (Tad McClellan)

Maybe it should be included in a perlfaq: how to populate a hash from
linefeed-ed data.


With a different separator:

#!/usr/bin/perl
use strict; use warnings;
use Data::Dumper;

my $sep = qr/ \s* : \s* /x;

my %person = map { chomp; split $sep } <DATA>;

print Dumper \%person;

__DATA__
name : fred
occupation : quarryman
friend : barney

--
Affijn, Ruud

"Gewoon is een tijger."


.