Perl在"if"之外匹配不会在循环中重置$ 1 [英] Perl match outside "if" doesn't reset $1 on loop

查看:117
本文介绍了Perl在"if"之外匹配不会在循环中重置$ 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在修补Zoidberg Perl shell,以修复现代Perl版本在测试时引发的一些错误.请注意,我既不是原作者,也不是在批评他.我遇到了一个有趣的问题,我希望对此进行一些回顾.

I am working on patching the Zoidberg Perl shell to fix some errors that modern Perl versions throw when testing. Note, I am not the original author nor am I criticizing him. I came upon an interesting problem that I would like a little history on.

下面的代码接受输入数组,每个输入剥离并结束标记.然后,如果没有找到该符号,则将其存储在变量中,而不是将其存储为0.原始文件中的代码看起来像测试A,并且必须工作到并包括给定的

The code below takes an array of inputs and for each strips off and ending sigil. Then it stores that sigil in a variable, if it didn't find it store 0 instead. The code that was in the original file looked like test A and must have worked until and including perl v5.8 given cpantesters results. Anyway the problem is that if the s/// isn't inside an of an "if" test, upon looping the $1 variable persists with the last value. Here are my tests. I was wondering if people could explain why this happens and or/why it used to work, I think I understand what is happening.

#!/usr/bin/perl

use strict;
use warnings;

my @a = qw/n a$ b@ c/;
my @b = @a;
my @c = @a;

print "Test A -- Doesn't work (c !-> 0)\n";
for (@a) {
  s/([\$\@\%])$//;
  my $arg = $1 || 0;
  print $_ . " -> " . $arg . "\n";
}

print "\nTest B -- Works\n";
for (@b) {
  my $arg;
  if (s/([\$\@\%])$//) {;
    $arg = $1;
  }
  $arg ||= 0;
  print $_ . " -> " . $arg . "\n";
}

print "\nTest C -- Works, more clever\n";
for (@c) {
  my $arg = s/([\$\@\%])$// ? $1 : 0;
  print $_ . " -> " . $arg . "\n";
}

推荐答案

来自 perlre :

注意: Perl中失败的匹配不会重置匹配变量,即 使编写代码更容易 针对一系列更具体的测试 记住并记住最佳匹配.

NOTE: Failed matches in Perl do not reset the match variables, which makes it easier to write code that tests for a series of more specific cases and remembers the best match.

但是您是对的,测试A的工作方式与5.8.9中的其他两个一样.我无法在 5.10.0发行说明中找到任何解释它的内容,但其中有很多RE在5.10中进行了更改,其中之一必须对此有所影响.我认为5.8行为不是故意的.

But you're right, Test A did work like the other two in 5.8.9. I can't find anything in the 5.10.0 release notes that explains it, but there were numerous RE changes in 5.10, and one of them must have affected this. I don't think the 5.8 behavior was ever intended.

这篇关于Perl在"if"之外匹配不会在循环中重置$ 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆