我应该如何使用 Perl 的标量范围运算符? [英] How should I use Perl's scalar range operator?
本文介绍了我应该如何使用 Perl 的标量范围运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
标量.."运算符的典型用法是什么?是只选择文本块吗?
What is the scalar ".." operator typical usage? Is it only selecting blocks of text?
我自己的有趣例子:
sub get_next {
print scalar($$..!$$), "\n";
}
get_next for 1 .. 5; # prints numbers from 1 to 5
get_next for 1 .. 5; # prints numbers from 6 to 10
推荐答案
根据这里的问题,人们似乎几乎不知道它,但是,是的,我会说典型的用法是选择文本块,或者使用
People hardly seem to know about it based on questions here, but, yes, I'd say typical usage is selecting blocks of text, either with
while (<>) {
print if /BEGIN/ .. /END/;
}
或
while (<>) {
print if 3 .. 5; # prints lines 3 through 5
}
后者是检查输入行号($.
)的语法糖
The latter is syntactic sugar for checking against the input line-number ($.
)
... if $. == 3 .. $. == 5;
这暗示着奇怪的外观
#! /usr/bin/perl -l
for ($_ = 1; $_ <= 10; ++$_) {
print if $_ == 4 .. $_ == 7;
}
上面程序的输出是
4
5
6
7
如果您有某种括号条件,请在 subs 中进行测试:
If you have some sort of bracketing condition, test for it in subs:
for (...) {
do_foo($x,$y,$z) if begin($x) .. end($z);
}
这篇关于我应该如何使用 Perl 的标量范围运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文