Question

I have the following code in my program, which aims to return the version and subversion of Debian installed. The output from shell is read by the variables and parsed and a string formed.

#!/usr/bin/perl
use warnings;
use strict;
use Scalar::Util qw(looks_like_number);
chomp(my $distver=`cat /etc/issue`);
$distver =~ s/\\n//g;
$distver =~ s/\\/./g;
$distver =~ s/ //g;
our $enpos=-1;
for ( my $i=0; $i <length($distver); $i++ ) {
    if (looks_like_number(substr($distver, $i, 1))) {
        if ( $enpos == -1 ) { $enpos = $i; }
    }
}
print "Distro:".substr($distver, 0, $enpos)."".substr($distver, $enpos);
my $subver=substr($distver, $enpos);
$subver =~ s/\\n//g;
$subver =~ s/\\r//g;
$subver =~ s/\\f//g;
print "Subversion:".$subver."\n";

The output of the above is:

root@der:~# ./distr.pl
Distro:DebianGNU/Linux7.l
Subversion:7.l

In the output, there is an additional newline at the end, after 7.1. I had tried the regexes above in attempt to remove newline, return and form feed characters at the end, but failed.

The output of cat /etc/issue is this.

I initially tried chomp to remove newline from the output, and found that instead of removing an ending newline, it did this:

print "Distro:".substr($distver, 0, $enpos)."".substr($distver, $enpos);
my $subver=chomp(substr($distver, $enpos));
print "Subversion:".$subver."\n";

Output:

root@der:~# ./distr.pl
Distro:DebianGNU/Linux7.l
Subversion:1
root@der:~#

So why is this happening? Why does chomp (and chop) cut off more than a newline? And why is this extra newline being output?

Was it helpful?

Solution

chomp changes the string in place, it does not return the changed string, but the number of characters removed.

To remove newlines, use s/\n//g, the double backslash matches backslash.

OTHER TIPS

Try it like this:

$distver =~ s/\n.*//s;

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