簡體   English   中英

perl,如何使用數組而不先將其分配給變量?

[英]perl, how do I use an array without assigning it to a variable first?

這是我目前在程序中所做的

@array = split /\n/, $longstring;
$data = $array[14];

我真的只想從數組中獲取第14位的元素並使用它,字符串中的其他內容對我沒有用。 我知道在像Java這樣的語言中我可以做這樣的事情

$data = (split /\n/, $longstring)[14];

這是我想做的,但要使用perl。

那么,如何在不必首先將數組分配給變量的情況下訪問數組元素?

編輯:嗯,好的

很長的路要走

my $data = "abc\nd^e^f\nghi";
my @a = split (/\^/, (split /\n/, $data)[1]);
print $a[2];
__OUTPUT__
f

捷徑

my $data = "abc\nd^e^f\nghi";
my $a = split (/\^/, (split /\n/, $data)[1])[2]; # line 60
print $a;
__OUTPUT__
syntax error at script.pl line 60, near ")["
Execution of script.pl aborted due to compilation errors.

這比平常更讓我困惑,因為它適用於內部拆分,但不適用於外部拆分

編輯2:

我對這兩條線為何不同感到困惑

my $a = (split  /\^/, (split /\n/, $data)[1])[2]; # works
my $a =  split (/\^/, (split /\n/, $data)[1])[2]; # doesnt

這是我對第二行的思考過程,這是我最初寫的(換句話說,這就是我認為我的程序正在做的事情)

my $data = "abc\nd^e^f\nghi";
my $a =  split (/\^/, (split /\n/, $data)[1])[2];
my $a =  split (/\^/, ("abc", "d^e^f", "ghi")[1])[2];
my $a =  split (/\^/, "d^e^f")[2];
my $a =  ("d", "e", "f")[2];
my $a =  "f";

那就是我期望發生的事情,有人可以指出我的想法出了問題嗎?

我將解釋這些行為何不同的原因:

my $r = (split  /\^/, (split /\n/, $data)[1])[2]; # works
my $r =  split (/\^/, (split /\n/, $data)[1])[2]; # syntax error
my $r = (split (/\^/, (split /\n/, $data)[1]))[2]; # but this works

在Perl中,您可以在括號中的列表(稱為列表切片 )上使用類似[2]的數組下標。 但是還有另一條規則說:“如果看起來像一個函數調用,那就是一個函數調用。” 也就是說,當您具有函數名稱(如split )后接可選的空格和右括號時,即為函數調用。 您不能對函數調用下標; 您需要在其周圍添加額外的一組括號。 這就是為什么我的第三行有效。

另一方面,您永遠不要說my $amy $b $a$b是與sort一起使用的特殊程序包變量,如果您將它們轉換為詞法,則會遇到奇怪的問題。 即使您目前不使用sort ,也可以稍后添加。 完全避免使$a$b詞法是最容易的。

為了提高可讀性,我可能會稍微調整空白並添加一條注釋:

my $r = (split /\^/, (split /\n/, $data)[1] )[2]; # get 3rd field of 2nd line

您剛剛將第一個(放錯了位置,請嘗試以下操作:

my $a = (split/\^/, (split /\n/, $data)[1])[2];

你寫的很好。

這是Codepad上的演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM