Jon Bot Jon Bot - 3 months ago 12
Perl Question

Data::Dumper wraps second word's output

I'm experiencing a rather odd problem while using Data::Dumper to try and check on my importing of a large list of data into a hash.

My Data looks like this in another file.

##Product ID => Market for product
ABC => Euro
PQR => India

Then in my script, I'm trying to read in my list of data into a hash like so:

open(CONFIG_DAT_H, "<", $config_data);
while(my $line = <CONFIG_DAT_H>) {
if($line !~ /^\#/) {
my @words = split(/\s*\=\>\s/, $line);
%product_names->{$words[0]} = $words[1];
print Dumper (%product_names);

My parsing is working for the most part that I can find all of my data in the hash, but when I print it using the Data::Dumper it doesn't print it properly. This is my output.

$VAR1 = 'ABC';
';AR2 = 'Euro
$VAR3 = 'XYZ';
';AR4 = 'USA
$VAR5 = 'PQR';
';AR6 = 'India

Does anybody know why the Dumper is printing the '; characters over the first two letters on my second column of data?


There is one unclear thing in the code: is *product_name a hash or a hashref?

  • If it is a hash, you should use %product_names{key} syntax, not %product_names->{key}, and need to pass a reference to Data::Dumper, so Dumper(\%product_names).

  • If it is a hashref then it should be labelled with a correct sigil, so $product_names->{key} and Dumper($product_names}.

As noted by mob if your input has anything other than \n it need be cleaned up more explicitly, say with s/\s*$// per comment. See the answer by ikegami.

I'd also like to add, the loop can be simplified by loosing the if branch

open my $config_dat_h, "<", $config_data  or die "Can't open $config_data: $!";

while (my $line = <$config_dat_h>) 
    next if $line =~ /^\#/;  # or /^\s*\#/ to account for possible spaces

    # ...

I have changed to the lexical filehandle, the recommended practice with many advantages. I have also added a check for open, which should always be in place.