假設文本被放入一個變量$信息,那麼你可以把它拆分成使用內部的Perl分割功能不同的行:
my @lines = split("\n", $info);
其中@lines是你的線條組成的數組。 「\ n」是換行符的正則表達式。可以通過每個線環如下:
foreach (@lines) {
$line = $_;
# do something with $line....
}
然後可以拆分上空白的每一行(正則表達式\ S +,其中\ s是一個空白字符,以及+是指1或大於1次):
@fields = split("\s+", $line);
和然後可以通過它的數組索引直接訪問每個字段:$字段[0],$字段[1]等
,或者可以這樣做:
($var1, $var2, $var3, $var4) = split("\s+", $line);
這將把每行中的字段放入單獨的命名變量中。
現在 - 如果你想排序您的線條在第三列中的字符,你可以這樣做:
my @lines = split("\n", $info);
my @arr =(); # declare new array
foreach (@lines) {
my @fields = split("\s+", $_);
push(@arr, \@fields) # add @fields REFERENCE to @arr
}
現在你有一個「數組的數組」。這可以很容易地排序如下:
@sorted = sort { $a->[2] <=> $b->[2] } @arr;
這將按@fields的第三個元素(索引2)排序@arr。
編輯2要放線,相同的第三列到自己的變量,這樣做:
my %hash =(); # declare new hash
foreach $line (@arr) { # loop through lines
my @fields = @$line; # deference the field array
my $el = $fields[2]; # get our key - the character in the third column
my $val = "";
if (exists $hash { $el }) { # check if key already in hash
my $val = $hash{ $el }; # get the current value for key
$val = $val . "\n" . $line; # append new line to hash value
} else {
$val = $line;
}
$hash{ $el } = $val; # put the new value (back) into the hash
}
現在你有一個第三列字符鍵,其值爲每個密鑰爲散列包含該鍵的行。然後,您可以遍歷散列並打印輸出或以其他方式使用散列值。
這些數據/行在哪裏?你的內部工具是否將它們放入單個變量中?或者,您需要閱讀文件中的文本數據? – 2009-12-12 16:04:33
該工具將它們放入單個變量中。 – scraft3613 2009-12-12 16:17:26
有Perl新手!!! 1 – nes1983 2009-12-12 16:23:44