Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

variables - How does --$| work in Perl?

Recently I came across this way to filter out every second value of a list:

perl -E 'say grep --$|, 1..10'
13579

How does it work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$| is a special Perl variable that can only have the values 0 and 1. Any assignment to $| of a true non-zero value, like

$| = 1;
$| = 'foo';
$| = "4asdf";          # 0 + "4asdf" is 4
$| = @a;

will have the effect of setting $| to 1. Any assignment of a false zero value

$| = 0;
$| = "";
$| = undef;
$| = "erk";            # 0 + "erk" is 0

will set $| to 0.

Expand --$| to $| = $| - 1, and now you can see what is going on. If $| was originally 1, then --$| will change the value to 0. If $| was originally 0, then --$| will try to set the value to -1 but will actually set the value to 1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...