-1

在编写脚本时,我注意到一些非常奇怪的 Perl 行为。任务是修剪存储在变量中的字符串的最后一个字符$temp1,这可以使用一个chop($temp1)或更复杂substr($temp1, 0, length($temp1) - 1)的 . 这些都作为单线工作,但在我的脚本中,substr解决方案不起作用。以下是调试器的示例:

第一个问题:

第一个解决方案 - 不工作:

main::(delmid_n.pl:24):     if (($state == 0) && ($_ !~ $musr) && ($_ !~ $lusr)) {
>> n
main::(delmid_n.pl:54):         $strprn=substr($temp1, 0, length($temp1) - 1);
>> p $temp1
                (-,user2,t-mobile.co.uk)\

>> p substr($temp1, 0, length($temp1) - 1) . "\n";
                (-,user2,t-mobile.co.uk)


  DB<4> 
main::(delmid_n.pl:55):     print $strprn . "\n";
  DB<4> 


main::(delmid_n.pl:56):         $temp1 = "";
  DB<4> 

正如您在$strprn变量中看到的那样,没有存储任何内容。如果通过“p”命令打印相同的代码(存储在$strprn变量中),则输出正常。可以使用上述chop()功能克服此“错误”(请参见下面的代码):

第二种解决方案 - 工作:

main::(delmid_w.pl:24):     if (($state == 0) && ($_ !~ $musr) && ($_ !~ $lusr)) {
>> p $temp1
                (-,user2,t-mobile.co.uk)\

  DB<4> n
main::(delmid_w.pl:56):     chop ($temp1);
  DB<4> n
main::(delmid_w.pl:57):     print $temp1;
  DB<4> n
                (-,user2,t-mobile.co.uk)
main::(delmid_w.pl:58):         $temp1 = "";
  DB<4>

上面的代码与第一个示例完全相同,但以下两行来自第一个示例:

$strprn=substr($temp1, 0, length($temp1) - 1);
print $strprn . "\n";

在第二个示例中替换为以下两行:

chop ($temp1);
print $temp1;

第二种解决方案有什么问题?

第二个问题:

到目前为止,这是一个我没有解决方法的问题。

 DB<1> 
main::(delbeg_n.pl:15): $state = 0;
  DB<1> 
main::(delbeg_n.pl:16): $muser = qr/\(-,user1,[^,]+\.co\.uk\)\\$/;
  DB<1> 
main::(delbeg_n.pl:19): line: while (<>) {
  DB<1> 
main::(delbeg_n.pl:20):     chomp;      # strip record separator
  DB<1> 
main::(delbeg_n.pl:21):     @Fld = split(/\s+/, $_,);
  DB<1> 
main::(delbeg_n.pl:23):     if (($state == 0) && ($Fld[1] =~ $muser)) {
  DB<1> p $Fld[1]        
(-,user1,one2one.co.uk)\

  DB<2> n
main::(delbeg_n.pl:43):         print $_;
  DB<2> p $_
netgroup1       (-,user1,one2one.co.uk)\

  DB<3> if ($Fld[1] =~ $muser) {print "TRUE"}
TRUE

正如您在代码中执行第 21 行后所看到的,下一个执行行是第 43 行(else 语句)。为什么以下条件没有被评估为真,允许代码从第 23、24、25 行继续?

if (($state == 0) && ($Fld[1] =~ $muser))

插入以下行是为了证明条件应该被评估为真:

if ($Fld[1] =~ $muser) {print "TRUE"}

非常感谢。

4

1 回答 1

1

这两个问题是相关的。行尾有一些奇怪的东西。

首先,看起来你在行尾的斜线后面有一个换行符,你没有把它切掉——至少调试器显示的是这样的:

>> p $temp1
                (-,user2,t-mobile.co.uk)\

  DB<4> n

如果没有换行符,它将是

>> p $temp1
                (-,user2,t-mobile.co.uk)\
  DB<4> n

所以,应该有两个字符:\和换行符。

为什么会出现这种奇怪的行为 - 如果不查看您的输入文件,我不知道。

此外,您可以不使用字符串长度,而是执行substr( $string, 0, -1 )-- 这也将返回除最后一个字符之外的所有字符。

这可能是您的第二个问题的原因——我猜这是匹配的,它是导致不匹配\(-,user1,[^,]+\.co\.uk\)\\的行尾标记。$

  • use strict
  • 检查文件类型(dos、unix、旧 mac)
  • 在十六进制编辑器中查看文件
于 2012-10-10T00:24:10.203 回答