0
#!/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
1
  • After your split statement, put this print statement to help figure out what is up...print "\n\t-- $_" foreach(@SplitArch); That will spill the contents of the array in the console, making it obvious why your code isn't working. Commented Aug 23, 2012 at 19:54

4 Answers 4

4

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`);
Sign up to request clarification or add additional context in comments.

Comments

1

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";

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.