views:

131

answers:

4

I'm capturing some output from an external program:

  my $cmd = "grep -h $text $file2 $file1 | tail -1 | awk '{print \$NF }' ";
  my $port_number;
  $port_number =`$cmd`;

  print "port No : ==$port_number==";

The output has extra whitespace around the port number:

port No : == 2323

==

and I tried chomp but it's not working.

+2  A: 

You can strip all whitespace with this:

$port_number =~ s/\s+//g;
eugene y
this sloved my issue
joe
@joe: ...which you still did not clearly state. Help others so that they can help you.
Ether
A: 

chomp only removes the last linebreak. Try a regex like this:

s/(?:\r?\n)*$//
jkramer
In Perl 5.10 of later, you can use the `\R` character class that matches generalized line endings. That would then be `s/\R+\z//;`
brian d foy
Sweet, didn't now that one. But I guess it's better to be one the safe side since 5.8 is still pretty popular.
jkramer
+1  A: 

I'm going to try to read your mind here and figure out what you mean by "its not working", by pointing you at the documentation for 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.

To use it correctly (assuming you want the rest of the string, not the newline), don't take its return value:

my $port = `$cmd`;
chomp $port;
print "$port\n";

You can remove any undesired surrounding whitespace with trim in the core module String::Util:

use String::Util 'trim';
trim $port;
Ether
`String::Util` is not a core module. If we are going to install a CPAN module, we might as well use the one that does the job the best: `String::Strip`. See http://www.illusori.co.uk/perl/2010/03/05/advanced_benchmark_analysis_1.html
daxim
@daxim: Module::CoreList tells me that String::Util has been in perl since 5.00x; perhaps I'm interpreting its results incorrectly.
Ether
You are mistaken: `Scalar::Util` ≠ `String::Util`
daxim
+4  A: 

One of your problems is that you don't need to use any external commands to do what you are doing. Stay inside Perl, which has the regex, file handling, and awk features built in:

my $last_matching_line;
{
local @ARGV = ( $file2, $file1 );

while( <> )
    {
    next unless /$text/;
    $last_matching_line = $_;
    }
}

my( $port_number ) = ( split /\s+/, $last_matching_line)[-1];

print "port No : ==$port_number==";
brian d foy