0

chomp function in Perl removes the record separator character (s) from a variable that appears at the end. However, in the following code, it remove more than that - it remove some characters from the front of the variable as well. Here is the code:

#!/usr/bin/env perl

use strict;
use warnings;
use String::Util qw(trim);
use feature 'say';

{
open FILE, "conf.txt" or die "Can't open file";
local $/ = ';';
my %hash;
my @val;

while (<FILE>){
    next if (/^\s+$/);
    @val=split /=/;
    $hash{$val[0]}=$val[1];
}

say $hash{"name1"};
say chomp $hash{"name1"};
close FILE;
}

The conf.txt file looks like so:

name1=va
l1;
name2=v
a
l2;
name3=val3;
name4=val4;

The output of the code is like so:

~ $ ./readconf.pl 
va
l1;
1

I was expecting that the output of say chomp $hash{"name1"}; would be va\nl1. Why does it just output 1?

Ketan Maheshwari
  • 2,002
  • 3
  • 25
  • 31

1 Answers1

6

From the manual:

It returns the total number of characters removed from all its arguments.

chomp modifies its argument in place. It doesn't return the possibly truncated string.

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254