Hidden features of Perl?
What are some really useful but esoteric language features in Perl that you've actually been able to employ to do useful work?
Guidelines:
Hidden Features also found in other languages' Hidden Features:
(These are all from Corion's answer)
Other Hidden Features:
Operators:
++
and unary -
operators work on strings m//
operator Quoting constructs:
Syntax and Names:
Modules, Pragmas, and command-line options:
overload::constant
Variables:
$[
variable Loops and flow control:
for
on a single variable Regular expressions:
G
anchor (?{})
and '(??{})` in regexes Other features:
DATA
block eof
function dbmopen
function Other tricks, and meta-answers:
See Also:
The flip-flop operator is useful for skipping the first iteration when looping through the records (usually lines) returned by a file handle, without using a flag variable:
while(<$fh>)
{
next if 1..1; # skip first record
...
}
Run perldoc perlop
and search for "flip-flop" for more information and examples.
There are many non-obvious features in Perl.
For example, did you know that there can be a space after a sigil?
$ perl -wle 'my $x = 3; print $ x'
3
Or that you can give subs numeric names if you use symbolic references?
$ perl -lwe '*4 = sub { print "yes" }; 4->()'
yes
There's also the "bool" quasi operator, that return 1 for true expressions and the empty string for false:
$ perl -wle 'print !!4'
1
$ perl -wle 'print !!"0 but true"'
1
$ perl -wle 'print !!0'
(empty line)
Other interesting stuff: with use overload
you can overload string literals and numbers (and for example make them BigInts or whatever).
Many of these things are actually documented somewhere, or follow logically from the documented features, but nonetheless some are not very well known.
Update: Another nice one. Below the q{...}
quoting constructs were mentioned, but did you know that you can use letters as delimiters?
$ perl -Mstrict -wle 'print q bJet another perl hacker.b'
Jet another perl hacker.
Likewise you can write regular expressions:
m xabcx
# same as m/abc/
Add support for compressed files via magic ARGV:
s{
^ # make sure to get whole filename
(
[^'] + # at least one non-quote
. # extension dot
(?: # now either suffix
gz
| Z
)
)
z # through the end
}{gzcat '$1' |}xs for @ARGV;
(quotes around $_ necessary to handle filenames with shell metacharacters in)
Now the <>
feature will decompress any @ARGV
files that end with ".gz" or ".Z":
while (<>) {
print;
}
链接地址: http://www.djcxy.com/p/42804.html
上一篇: HTML的隐藏功能
下一篇: Perl的隐藏功能?