関数順 インデックス
目的別 インデックス

構文
 
 qx/コマンド/

返り値
 
 コマンドの実行結果

説明

  • 指定したコマンドを実行して,標準出力に出力された結果を返します。
  • 呼び出したコマンドのステータス・コードは$?で取得することができます。$?にはステータス・コードを256倍した値が入っていますので,例えば,ステータス・コード1で終了した場合,$?は256になります。

使用例

コマンドnetstatを実行して実行結果を出力する
#!/usr/bin/perl
use strict;
use warnings;

# 実行するコマンド
my $command = 'netstat'; 

# コマンドを実行
my $ret = qx/$command/; 
if ($?) {
  # ステータスコードが0以外
  print "Error.\n";
  print "$command:$?", "\n";
} else {
# 実行結果を出力する
  print $ret, "\n"; 
}
コマンドnetstatを実行して実行結果を出力する(`を使用)
#!/usr/bin/perl
use strict;
use warnings;

my $command = 'netstat'; 
my $ret = `$command`; 
if ($?) {
  print "Error.\n";
  print "$command:$?", "\n";
} else {
  print $ret, "\n"; 
}
コマンド/bin/lsを実行して実行結果を出力する(qxでスラッシュ以外の記号を使う)
#!/usr/bin/perl
use strict;
use warnings;

my $ret = qx{/bin/ls}; 
if ($?) {
  print "Error.\n";
  print "$?", "\n";
} else {
  print $ret, "\n"; 
}