2013-02-12 48 views
-2

我在學校和網絡編程課。我根本沒有Perl經驗。我們的任務如下。基本的Perl作業

編寫一個使用反引號``函數運行外部命令ps -aux的短程序,以列出用戶擁有的所有當前正在運行的進程,其用戶名作爲命令行參數提供。

提示:

$ARGV[0] or die "without a username given\n"; 
my $.... = $ARGV[0]; 
my @ps = `ps -axu`; 
foreach my $..... (@ps) { 
print $line if …../; 
} 

我已經改變了代碼如下:

#!/usr/local/bin/perl -w 
use strict; 
use warnings; 
my $line; 

$ARGV[0] or die "without a username given\n"; 
my $test = $ARGV[0]; 
my @ps = `ps -axu`; 
foreach my $test (@ps) { 
print $line if ...../; 
} 

不過,我不斷收到此錯誤:

語法錯誤在C:\ Perl的\ W4A2new。 pl line 10,near「if ...」 Search pattern not end at C:\ Perl \ W4A2new.pl line 10.

任何人都可以幫我嗎?請。謝謝。

+0

你有10號線附近的「如果」有語法錯誤。與你的正則表達式(搜索)模式有關。嘗試發佈您的實際代碼。 – 2013-02-12 22:55:11

回答

0
#!/usr/local/bin/perl -w 
use strict; 
use warnings; 


my $username = $ARGV[0] or die "without a username given\n"; 
my @ps = `ps -axu $username`; 
foreach my $line (@ps) { 
    print $line, "\n"; 
} 

你必須用這種方式執行這個腳本(假設腳本名稱是myscript.pl):

perl myscript.pl your_operating_system_user_name 
+0

我收到消息「錯誤:必須設置個性才能獲得-x選項。「 - 同樣,如果我只是在shell中直接鍵入」ps -axu $ myusername「...在標準的ubuntu上 – 2013-02-12 22:57:41

+0

perl myscript.pl your_user_name – 2013-02-12 22:59:34

+0

對我不起作用...請參閱我的編輯 – 2013-02-12 23:00:13

0
  1. ps命令通常是調用像ps aux(無前導負)。
  2. 在ps參數中指定用戶名不起作用我可以看到
  3. 使用反引號很方便,但可以認爲是不好的樣式。
  4. ps aux輸出的第一列可以包含數字用戶標識。
  5. 我們可以使用/etc/passwd在用戶ID和用戶名之間進行翻譯。

這裏是代碼打印出帶有指定字符串開頭的所有ps行:

#!/usr/bin/perl 
use strict; use warnings; 

print grep /^\Q$ARGV[0]\E/, `ps aux`; 

最後一行可以詳細寫到:

my @temp; 
for (`ps aux`) { 
    push @temp, $_ if /^\Q$ARGV[0]\E/; 
} 
print @temp; 

該腳本將被調用像perl script.pl rootperl script.pl 1000

正如我所說的,我們可以在用戶名和用戶ID之間進行翻譯。另外,我們可以將ps輸出視爲它的列數據。柱子是

USER  PID %CPU %MEM VSZ RSS TTY  STAT START TIME COMMAND 

我們可以通過my @cols = split ' ', $line, 11訪問這些的cols。我們必須指定最大列數,因爲該命令可能包含空格。如果用戶只包含數字字符,我們翻譯成相應的名稱/etc/passwd

#!/usr/bin/perl 
use strict; use warnings; 

my $username = $ARGV[0] or die <<"END_USAGE"; 
USAGE: perl $0 USERNAME 
    USERNAME -- the full username you want ps output for. 
END_USAGE 

my %id_2_name = do { 
    open my $passwd, "<", "/etc/passwd" or die "Can't open passwords: $!"; 
    map { (split /:/)[2,0] } <$passwd>; 
}; 

open my $ps, "-|", "ps", "aux" or die "Can't open ps command: $!"; 

while(<$ps>) { 
    my @cols = split ' ', $_, 11; 
    $cols[0] = $id_2_name{$cols[0]} unless $cols[0] =~ /[^0-9]/; 
    print join " ", @cols if $cols[0] eq $username; 
} 
+0

Amon,謝謝你,不過,我一直把'ps'作爲內部或外部命令,可操作的程序或批處理文件來識別。 – 2013-02-17 18:18:23

+0

@JeffreyLocke你在什麼操作系統上? d在Ubuntu GNU/Linux下的腳本;它工作正常。 Windows沒有'ps'。 Windows也沒有'/ etc/passwords' ...你不能在Windows下開發Unix或類Unix系統的程序(Cygwin層除外)。 – amon 2013-02-17 18:53:08

+0

我在網絡編程類。他們讓我們使用Perl。 – 2013-02-18 03:10:00