Perl 程式中包含美元 ($) 符號的簡單文本字串:
open my $fh, "<", $fp or die "can't read open '$fp': $OS_ERROR";
while (<$fh>)
{
$line=''; #Initialize the line variable
$line=$_; #Reading a record from a text file
print "Line is $line\n"; #Printing for confirming
(@arr)=split('\|',$line);
$line 獲取以下管道分隔的字串(通過列印 $line 值確認):
Vanilla Cake $3.65 New Offering|Half pound Vanilla Cake||Cake with vanilla, cream and cheese
然后將該記錄拆分并拉入特定的陣列元素:
(@arr)=split('\|',$line);
$arr[0] 得到Vanilla Cake $3.65,$arr 
uj5u.com熱心網友回復:
這段代碼
if ($foo =~ /(.*?)(\$\d (?:\.\d )?)/) {
print "match1 is $1, match2 is $2, match3 is $3, match4 is $4\n";
}
有了這個輸入
Vanilla Cake $3.65
將列印
Use of uninitialized value $3 in concatenation (.) or string at ...
Use of uninitialized value $4 in concatenation (.) or string at ...
match1 is Vanilla Cake , match2 is $3.65, match3 is , match4 is
如果您沒有use warnings啟用,警告將保持沉默。
這就是您提供的代碼對此輸入的作用。您還表明它與您的螢屏截圖有關。您在評論中說,它不會在您的家用 PC 上執行此操作。我會說這是不可能的。
您的代碼不同,您的輸入不同,或者您的 Perl 安裝不同(盡管這不太可能是問題)。真的別無選擇。
一個大問題是您沒有使用use strict; use warnings您的代碼。這可能意味著您的代碼的任何數量的問題都被隱藏了。在您的情況下,我很可能會說這是一個錯字,例如:
$Iine = $_;
if ($line =~ /...../) # <---- not the same variable
但是您要求 8 小時更新您的代碼,所以我想我們會在 8 小時內找到答案。
幾點建議
while (<$fh>)
{
$line=''; #Initialize the line variable
$line=$_; #Reading a record from a text file
- 您不需要“初始化”行變數。下一行將使該行完全多余。
- 該行實際上并沒有從您的檔案中讀取記錄,readline 陳述句
<$fh>正在執行此操作。 - 通常你會把這一行寫成:
while (my $line = <$fh>). $3并且$4在您的列印陳述句中永遠不能保存一個值,因為您缺少( ... )必要的捕獲組。兩個捕獲組僅表示$1并且$2將被填充。
撰寫 Perl 代碼時,應始終使用
use strict;
use warnings;
因為不這樣做不會幫助你,它只會隱藏你的問題。
還要養成將宣告 ( my $var) 放在盡可能小的范圍內的習慣。示例代碼:
use strict;
use warnings;
use feature 'say';
while (my $line = <DATA>) {
my @x = split /\|/, $line;
if ($x[0] =~ /(.*?)(\$\d (?:\.\d )?)/) {
say "$1 is $2";
}
}
__DATA__
Vanilla Cake $3.65 New Offering|Half pound Vanilla Cake||Cake with vanilla, cream and cheese
uj5u.com熱心網友回復:
大約 2 年前,我遇到了一個類似的問題 - 并且不得不打破我的頭超過 5 天,然后我才能用巨大的 $ 符號找到問題的根源。事情是這樣的:
美元正則運算式值未列印 - 類似于您所觀察到的。
很久以前有人撰寫的 perl 代碼用雙引號初始化了字串 var。就像是
$string="This is some text";
在我觸摸它之前它作業得很好。:-)
我所做的是在其中插入了一個變數,例如
$string="This is some $PriceVariableHavingDollarSign text";
然后我嘗試在 $string 變數上運行與美元匹配的正則運算式,希望能檢測到美元。不完全是,但與您嘗試執行的操作非常相似,如下所示:
$string=~ /(.*?)(\$\d (?:\.\d )?)/
它要么給出編譯錯誤,要么無法使用我嘗試的不同正則運算式組合完全拾取美元符號。
所以我的回答兼建議是檢查你的“冗長代碼”,如果你的變數上的雙引號發生了類似的事情。最有可能的是,這可能會導致問題。
在從源頭獲取值之前,如果可能,請嘗試在 $ 符號上使用 \,例如(至少這解決了我的問題)。代替
PriceVariableHavingDollarSign = "Cake is $3.5";
嘗試擁有
$PriceVariableHavingDollarSign ="Cake is \$3.5";
這是對 Perl 中雙引號和單引號發生的情況的一個很好的解釋。 https://www.effectiveperlprogramming.com/2012/01/understand-the-order-of-operations-in-double-quoted-contexts/
對于您在問題、評論和圖片中提出的明確細節,做得很好。它可以幫助您獲得所有可能的角度、場景和解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/483405.html
上一篇:Perl:陣列參考的負范圍索引
