jrock2004
jrock2004

Reputation: 3501

Perl split a string

#!/usr/bin/perl
$command="lscpu | grep -i Architecture";
#$arch = system($command);
@SplitArch = split(/:/, system($command));
print @SplitArch[1];

The result I get is:

Architecture:          x86_64

I was hoping that the only thing that would display is:

x86_64

Upvotes: 0

Views: 245

Answers (4)

ruakh
ruakh

Reputation: 183582

This doesn't do what you think it does. The system function runs the command and returns its exit status; so in your case, this:

system($command)

prints Architecture: x86_64, so this:

@SplitArch = split(/:/, system($command));

prints Architecture: x86_64 and sets @SplitArch to (0).

print @SplitArch[1] then prints nothing, because @SplitArch has only one element. (By the way, you probably meant to write $SplitArch[1] rather than @SplitArch[1], but that's neither here nor there.)

Since you apparently intend to capture the output of $command, use `...` or qx/.../ instead:

@SplitArch = split(/:/, `$command`);

Upvotes: 4

ikegami
ikegami

Reputation: 386676

Explanation already given — system doesn't return what you think it does — I'm just providing an alternative solution.

open(my $LSCPU, '-|', 'lscpu') or die $!;
while (<$LSCPU>) {
   chomp;
   my ($key, $val) = split(/:\s*/, $_, 2);
   if ($key eq 'Architecture') {
       print "$val\n";
       last;
   }
}
close($LSCPU);

Advantages:

  • Exits ASAP.
  • Doesn't involve the shell.
  • Involves one less external program aside from the shell.
  • More precise matching of desired line.

Upvotes: 0

EMiller
EMiller

Reputation: 2842

I believe the return value of System is the exit value of the command, not the output.

You should perhaps do:

$output = `$command`;
@SplitArch = split(/:/, $output);

Hope this helps.

Upvotes: 0

amon
amon

Reputation: 57650

If you want to get the output of a command, you should use the qx{} operator:

my @SplitArch = split /:/ qx{$command};

And to print the value at array index #1, you should use the $ Sigil as you expect a scalar value:

print $SplitArch[1], "\n";

Upvotes: 1

Related Questions