Question

In my code I assign a variable disc to equal the result of an command disc on my linux system. This outputs the string RESEARCH

my $disc = `disc`;
print "$disc\n";
$disc = chomp($disc);
print "$disc\n";

However when I use chomp to strip the newline character from the string it changes the string to 1. Here is the output

RESEARCH

1

What is going on?

Was it helpful?

Solution

From perldoc -f chomp:

chomp VARIABLE
chomp( LIST )
chomp   This safer version of "chop" removes any trailing string that
        corresponds to the current value of $/ (also known as
        $INPUT_RECORD_SEPARATOR in the "English" module). It returns the
        total number of characters removed from all its arguments. 

The proper usage is to simply provide a variable or list that will be altered in place. The return value, which is what you use, is how many times it "chomped" its argument list. E.g.

chomp $disc;

Or even:

chomp(my $disc = `disc`);

For example, you may chomp an entire array or list, e.g.:

my @file = <$fh>;          # read a whole file
my $count = chomp(@file);  # counts how many lines were chomped

Of course, with a single scalar argument, the chomp return value can be only 1 or 0.

OTHER TIPS

Avoid assigning the chomp result to your variable:

$disc = chomp($disc);

use:

chomp($disc);

This is because chomp modifies the given string and returns the total number of characters removed from all its argument

Just use chomp $disc without any affectation beacause chomp returns the number of chars removed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top