Perl的tr ///没有做我想要的 [英] Perl's tr/// is not doing what I want

查看:143
本文介绍了Perl的tr ///没有做我想要的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:tr ///不支持变量插值,所以我以 s / \Q $ _\E // g; 代替



或者,更有可能我没有做正确的事情...



我有以下代码: p>

 #!/ usr / bin / perl 

use strict;
使用警告;
使用utf8;

sub strip_invalid {
my($ str,@chars)= @_;

map {$ str =〜tr / $ _ //; } @chars;

return $ str;
}

我的@invalid = qw(a e i o u);

print strip_invalid(这是带有元音的超级样本,\\\
,@invalid);

我只想传递一个字符串到 strip_invalid()并且具有 tr /// 通过 @invalid 中的字符>地图 ...哪里出错? (顺便说一下,使用正则表达式)。

解决方案

Perl的 tr 功能不支持变量


请注意,由于翻译表是在编译时构建的,因此SEARCHLIST和REPLACEMENTLIST都不会进行双引号插值。这意味着如果要使用变量,则必须使用eval():




  evaltr / $ oldlist / $ newlist /; 

(来源)


EDIT: tr/// does not support variable interpolation, so I went with s/\Q$_\E//g; instead

Or, more likely, I'm not doing something right...

I have the following code:

#!/usr/bin/perl

use strict;
use warnings;
use utf8;

sub strip_invalid {
  my ($str, @chars) = @_;

  map { $str =~ tr/$_//; } @chars;

  return $str;
}

my @invalid = qw( a e i o u );

print strip_invalid("This is the super sample with vowels.\n", @invalid);

I'd just like to pass a string to strip_invalid() and have tr/// remove the characters in @invalid through a map... Where did I go wrong? (by the way, using regular expressions it works).

解决方案

Perl's tr feature doesn't support variables.

Note that because the translation table is built at compile time, neither the SEARCHLIST nor the REPLACEMENTLIST are subjected to double quote interpolation. That means that if you want to use variables, you must use an eval():

eval "tr/$oldlist/$newlist/";

(Source)

这篇关于Perl的tr ///没有做我想要的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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