Reputation: 23
Hello I am trying to print the values and keys of a hash with one key/value per row like this:
key:value
This is the code I am using to print my hash:
foreach (sort keys %hash) { print "$_:$hash{$_}\n"; }
And this is the output I get:
key
:value
Why is my script printing the value on a new row and what can I do to fix it?
Upvotes: 1
Views: 865
Reputation: 4175
Try this version of printing loop:
foreach (sort keys %hash) {
my $v = $hash{$_};
s/\s+$//;
print "$_:$v\n";
}
Keys in %hash definitely have some unwanted trailing characters, so it is better to filter them out when %hash is filled. For example instead of this:
@hash{@keys} = @vals;
Write this:
@hash{map { s/\s+$//; $_ } @keys} = @vals;
Or this:
chmop(@keys);
@hash{@keys} = @vals;
But chomp
will not help with multiple characters.
Upvotes: -2
Reputation: 385809
The cursor is moving to the next line because your key contains a line feed. The solution is to remove the line feed from the key.
More specifically, you surely want to avoid creating a key with a line feed in the first place, so it should be removed from the key before you create the hash element.
You're presumably reading the key from a file handle. It's customary to use chomp
(to remove any trailing line feed) or s/\s+/z//
(to remove any trailing whitespace including line feeds).
my @keys;
while (<>) {
chomp; # Or: s/\s+\z//;
push @keys, $_;
}
my %hash; @hash{@keys} = @values;
Upvotes: 1