为什么我在 perl 中从 s、y 和 tr 运算符得到不同的结果?

问题描述 投票:0回答:2

perl -pe 's/A/ā/' <<< "avatAr"
按预期给了我
avatār

但是

perl -pe 'y/A/ā/' <<< "avatAr"
perl -pe 'tr/A/ā/' <<< "avatAr"
都给我
avat�r
.

为什么会这样?我怎样才能得到与替换相同的结果?

我也试过

perl -Mutf8 -C24 -pe 'tr/A/ā/' <<< "avatAr"
它给了我

Wide character in print at -e line 1, <> line 1.
avatār

收到此警告我做错了什么?

y
而不是
tr
.

的相同结果
perl tr string-substitution
2个回答
0
投票

除了像kaavannan解释的那样需要

-Mutf8
之外,您还会收到“宽字符”警告,因为
-C24
中的数字是数字,而不是标志,所以应该写成
-C6
。更好的方法是使用标志并启用 stderr:
-CS
.


0
投票

你可以像下面这样使用 tr

perl -Mutf8 -C24 -pe 'tr/A/ā/' <<< "avatAr"  

-C24 可以用 -CS 替换然后它按预期工作

输出:

avatār

理解为什么在 Perl 中使用 s、y 和 tr 运算符时会产生不同的结果可能会令人困惑。本文将解释每个运算符的工作原理以及何时应使用每个运算符来获得预期结果。

运算符 s/search/replace/ 用于替换,是最常见的运算符。它搜索名为“search”的子字符串或正则表达式 (regex),如果找到,则将其替换为“replace”。例如,s/A/ā/ 会查找任何出现的大写字母“A”并将其替换为对应的小写字母“ā”。在这种情况下,运行 perl -pe 's/A/ā/' <<< "avatAr" would give you avatār as expected.

运算符 y/thisstring1/thatstring2/ 和 tr/thisstring1/thatstring2 的功能类似于替换运算符,但有一个主要区别:它们作用于单个字符而不是字符串或正则表达式。这些命令将搜索一个字符串,用它在字符串 thatstring2 中的对应字符替换所有出现的字符 thisstring1。如果一个字符在任一字符串中出现多次,则每次出现都将按从左到右的顺序替换为相应的字符。例如,运行 perl -pe 'yABCDEFGabcdefgXVYVWX' <<< "avatAr" would match every occurrence of "A" from left to right within both strings so that A gets replaced by A, B gets replaced by b, C gets replaced by c etc., until it reaches X which is then replaced by V etc., resulting in avatVr which does not match your expected result for this particular example.

您在运行 perl -Mutf8 -C24 -pe 'tr/A/ā//' 时收到的警告消息可能是由于您尝试对 Unicode UTF-8 进行编码但系统上未启用 Unicode 或您没有指定附加标志,例如“U”(明确包含 Unicode 字符)。如果您的系统未启用 Unicode UTF-8 支持,尝试在两个 Unicode 字符之间进行 tr 操作可能会导致出现此错误消息。

使用 Perl 时,重要的是要知道应该使用哪个运算符,这取决于您需要什么类型的替换以及是否需要启用 Unicode 支持。使用正确的运算符组合应该可以让您获得所需的结果而不会出现任何错误。

关注这篇有帮助的帖子utf8

© www.soinside.com 2019 - 2024. All rights reserved.