liyana ross
liyana ross

Reputation: 23

Concatenate Variable in Perl

Below is my code. Supposedly I wanted to concatenate the variable $process with the text "processes running".

my $process =`ps aux | grep '[c]pu2006' -c `;

my $process2= "$process" . " processes running\n";

print $process2;

I want the output to be:

3 processes running

But it turned out to be:

3   
processes running

Can someone help me with this code?

Upvotes: 1

Views: 150

Answers (1)

John C
John C

Reputation: 4396

Your $process variable contains a number 3 and a line feed.

You can remove the linefeed with chop or chomp.

So your script becomes:

my `$process =ps aux | grep '[c]pu2006' -c`;
chomp($process);
my $process2= "$process" . " processes running\n";
print $process2;

chop and chomp are a bit confusing...

If you are using unix you can use chop because unix uses only '\n' as a line separator.

If you are using windows you can use chomp because chomp is smart enough to know what the input line separator is and will remove two characters \r and \n.

Best practice is to use chomp.

If you want to clean it up a bit you could also say:

chomp (my $process =`ps aux | grep '[c]pu2006' -c`);
print "$process processes running\n";

Upvotes: 5

Related Questions