使用“for"对变量进行主题化显然是坏的.为什么? [英] Topicalising a variable using "for" is apparently bad. Why?

查看:85
本文介绍了使用“for"对变量进行主题化显然是坏的.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我回答了一个关于 SO 的问题,并因此受到了很多批评.我已经使用 Perl 很多年了,并且经常使用这个话题.

So I answered a question on SO and got a lot of flack for it. I have been using Perl for many years and use this topicalising quite a lot.

让我们从一些代码开始.我正在这些示例中进行搜索和替换.这个想法是从两个字符串中搜索 onethree 并替换它们.

So let's start with some code. I am doing search and replace in these examples. The idea is to search for one and three from two strings and replace them.

$values = 'one two three four five';
$value2 = 'one 2 three four 5';

$values =~ s/one//g;
$values =~ s/three//g;

$values2 =~ s/one//g;
$values2 =~ s/three//g;

这段代码很简单,大家都能接受.

This code is simple and everyone accepts it.

我还可以构建一个包含要搜索和替换的值列表的数组或散列,这也是可以接受的.

I can also build an array or hash with a list of values to search and replace which is also acceptable.

然而,当我构建一个脚本来主题化 $values$values2 并减少输入量来构建脚本时,它似乎被误解了?

However, When I build a script to topicalise $values and $values2 and lessen the amount of typing to build a script it seems to be misunderstood?

这是代码.

$values = 'one two three four five';
$value2 = 'one 2 three four 5';

for ( $values, $values2 ) {
    s/one//g;
    s/three//g;
}

上面的代码将在 for 块的持续时间内对变量进行主题化,但许多程序员反对这一点.我想了解为什么这是不可接受的?

The above code will topicalise the variables for the duration of the for block, but many programmers are against this. I want to understand why this is unacceptable?

推荐答案

perldoc perlsyn 有这个

foreach 是设置主题化器的非实验方式.

The foreach is the non-experimental way to set a topicalizer.

OP 的构造是编写 Perl 代码的一种完全有效的方式.我对他们早期答案的唯一规定是

The OP's construct is a perfectly valid way of writing Perl code. The only provisons I have regarding their earlier answer are

  • 与此处的示例不同,只有两个操作应用于单个变量.这只是比简单地写两个替换稍微简短一点,我不会在这里打扰,尽管我可能考虑

s/one//g, s/three//g for $value;

  • 除了话题之外,答案与另一个已经发布的答案相同.我不认为这足以保证另一篇文章的不同

  • Other than the topicaliser, the answer is identical to another one already posted. I don't believe this makes it sufficiently different to warrant another post

    这篇关于使用“for"对变量进行主题化显然是坏的.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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