gpt4 book ai didi

perl - 这个 Perl 语句是什么意思?

转载 作者:行者123 更新时间:2023-12-01 06:43:14 25 4
gpt4 key购买 nike

我正在尝试将 Perl 脚本解析为 Python。我几乎没有使用 Perl 的经验,但它仍然非常顺利。 Perl 文档庞大而令人印象深刻。但是,有时我真的无法弄清楚一些非常神秘的语法,并且我无法与脚本的作者交流。下面的内容让我头疼了好久:

sub someSubroutine
{
my ($var1, $var2, $var3) = @_;

# some Perl code

$var2 =~ s|/|\\|g;

# and then some more code ..
}

我真的不明白这一特别而孤独的台词

$dst =~ s|/|\\|g;

我很清楚它在 $var2 中使用一些二进制 OR 操作进行搜索/字符串匹配,但结果未存储。

不知道是不是有什么不那么明显的副作用,比如会不会自动存入$_

根据我的阅读,默认变量是在调用子例程、启动循环或类似情况时自动设置的,但在使用运算符时则没有。

非常感谢任何帮助或指向适当文档的指针。

最佳答案

$var2 =~ s|/|\\|g;

s/pattern/replacement/substitution operator .

Searches a string for a pattern, and if found, replaces that pattern with the replacement text and returns the number of substitutions made. Otherwise it returns false (specifically, the empty string).

| 不是“binary or”——它是一个分隔符。在 s 中,您可以使用任何分隔符,尤其是为了便于阅读。

来自 perlop Regexp Quote-Like Operators

Any non-whitespace delimiter may replace the slashes. Add space after the s when using a character allowed in identifiers. If single quotes are used, no interpretation is done on the replacement string (the /e modifier overrides this, however). Note that Perl treats backticks as normal delimiters; the replacement text is not evaluated as a command. If the PATTERN is delimited by bracketing quotes, the REPLACEMENT has its own pair of quotes, which may or may not be bracketing quotes, for example, s(foo)(bar) or s/bar/.

上面将 $var2 中的每个 / 替换为 \。 (\ 是转义字符,所以需要使用\\)。

my $v='/a/b/c';
$v =~ s|/|\\|g;
print "$v\n";
# \a\b\c

还有,

If no string is specified via the =~ or !~ operator, the $_ variable is searched and modified.

$_ = $v;     # assign the $_
s{\\}{/}g; # substitution on the $_ using bracketed delimiters
print; # without args prints the $_
# /a/b/c

关于perl - 这个 Perl 语句是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43181102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com