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

查看:30
本文介绍了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,并且在给定 cpantesters 结果.无论如何,问题是如果 s///不在if"测试中,则在循环时 $1 变量将保持最后一个值.这是我的测试.我想知道人们是否可以解释为什么会发生这种情况和/或为什么它曾经起作用,我想我明白发生了什么.

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)
";
for (@a) {
  s/([$@\%])$//;
  my $arg = $1 || 0;
  print $_ . " -> " . $arg . "
";
}

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

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

推荐答案

来自 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天全站免登陆