2011-05-06 44 views
24

在其他語言中,我使用的就像Erlang和Python,如果我分割字符串而不關心其中一個字段,則可以使用下劃線佔位符。我在Perl試過這樣:使用虛擬佔位符的Perl分配

(_,$id) = split('=',$fields[1]); 

,但我得到了以下錯誤:

Can't modify constant item in list assignment at ./generate_datasets.pl line 17, near ");"
Execution of ./generate_datasets.pl aborted due to compilation errors.

還包括Perl有,我可以改用創建一個無用的臨時變量的類似這樣的模式?

回答

37

undef在Perl中的作用相同。

(undef, $something, $otherthing) = split(' ', $str); 
+9

注意:即使在聲明中有效'my(undef,$ a,$ b)= ...' – ysth 2011-05-06 21:27:52

+4

我想投票贊成,但使用'$ a'和'$ b'可以防止我。 – darch 2011-05-06 23:25:16

+3

@darch:* eyeroll * – geekosaur 2011-05-06 23:27:23

17

如果使用Slices你甚至都不需要佔位符:

use warnings; 
use strict; 

my ($id) = (split /=/, 'foo=id123')[1]; 
print "$id\n"; 

__END__ 

id123 
8

您可以分配到(undef)

(undef, my $id) = split(/=/, $fields[1]); 

你甚至可以使用my (undef)

my (undef, $id) = split(/=/, $fields[1]); 

你也可以使用列表片。

my $id = (split(/=/, $fields[1]))[1]; 
1

而只是爲了解釋爲什麼你,你看到的特定錯誤...

_是內部Perl的變量,可以在stat命令可以作爲我們用來表示「相同的文件在前面的stat呼叫「。這樣Perl會使用一個緩存的stat數據結構,並且不會再調用其他的stat

if (-x $file and -r _) { ... } 

此文件句柄是一個常數值,不能寫入。變量存儲在與$_@_相同的類型球體中。

請參閱perldoc stat