操作符有状态行为的详细信息,如 match (ie. m//g)、stat (ie. stat _) 和 range (ie. //..//) 在文档中。但是,是否有所有表现出有状态行为的运算符或函数的“列表”?想到的有:
#ARGV/File/dir/glob: The current line/position is remembered
say while <>; #Read line by line by Line from ARGV files
say while <$fh>; #Read line by line by line from file handle
say while defined($_ = readdir($dh)); #Read an entry at a time from dir handle
say while <*>; #Read an entry at a time from file glob in current dir
say while <{a,b,c},{1,2}>; #Print combination glob one at a time ie (a1,b1,c1,a2,b2,c2)
#Regex: Global modifier/list context remembers previous matches
say while m/$re/g; #Print matches one at a time
my $_="hello"; say /hello/g; say /hello/gc; #Only prints hello once. Stateful continuation from last match position
#stat
stat _; #Returns stat array state from previous stat "filename";
#range: State remembers if the first condition is met
perl -n -e 'print if 1..10' myfile.txt; #Bistable flipflop state. Print lines 1 to 10
perl -n -e 'print if /startmatch/../endmatch/' myfile.text; #print lines between matches
#state variable: make your own
sub { state $myStateVar;}; #Your own state variable
Any info would be great. Thanks
Run Code Online (Sandbox Code Playgroud)
共有三个有状态运算符。
glob在标量上下文中(包括<>用作glob)。
for my $pass (1..2) {
say glob("abc") // "[undef]";
}
Run Code Online (Sandbox Code Playgroud)
输出
abc
[undef]
Run Code Online (Sandbox Code Playgroud)
触发器操作者(..和...在标量上下文)。
for my $pass (1..2) {
$. = 5;
say scalar(5..6);
}
Run Code Online (Sandbox Code Playgroud)
输出
1
2
Run Code Online (Sandbox Code Playgroud)
state
for my $pass (1..2) {
state $x = "abc";
say $x;
$x = "def";
}
Run Code Online (Sandbox Code Playgroud)
输出
abc
def
Run Code Online (Sandbox Code Playgroud)
许多操作员使用TARG使他们在技术上有状态的机制,但这是一种对用户透明的优化。该机制允许运算符记住它们返回的标量,以便后续调用可以重用它。
perl -e'
use Devel::Peek qw( Dump );
for my $pass (1..2) {
my $x = "abc";
Dump(uc($x));
}
' 2>&1 | grep -P '^SV ='
Run Code Online (Sandbox Code Playgroud)
输出
SV = PV(0x55d87231fea0) at 0x55d87237ce08
SV = PV(0x55d87231fea0) at 0x55d87237ce08
Run Code Online (Sandbox Code Playgroud)
两个标量位于同一地址 ( 0x55d87237ce08)并非巧合;这是同一个标量。
有人建议m//g在标量上下文中是有状态的,但其结果严格基于其输入。观察到的效果是使用的结果pos($_),其中$_是输入。
local $_ = "abcdef";
for my $pass (1..2) {
pos($_) = 2;
last if !/./g;
say $&;
}
Run Code Online (Sandbox Code Playgroud)
输出
c
c
Run Code Online (Sandbox Code Playgroud)
有人建议它each是有状态的,但其结果严格基于其输入。观察到的效果是使用作为输入一部分的迭代器的结果。
my %h = ( a=>1, b=>2, c=>3 );
for my $pass (1..2) {
keys(%h); # `keys` in void context resets a hash's iterator.
say join " ", each(%h);
}
Run Code Online (Sandbox Code Playgroud)
输出
c 3
c 3
Run Code Online (Sandbox Code Playgroud)
keys并values使用相同的迭代器。
有人建议readline和readdir是有状态的,但他们的结果严格基于他们的输入。您获得不同输出的唯一原因是每次输入(文件句柄或目录句柄)都不同。
这些函数(和许多其他函数)有副作用,这些副作用包括修改它们的输入。但我不会称它们为有状态的,因为这些操作符和有状态的操作符之间存在显着差异。
stat是有状态的,但其结果严格基于其输入(无论是它_还是其他东西)。这不是最有状态的。
| 归档时间: |
|
| 查看次数: |
192 次 |
| 最近记录: |