Wednesday, July 8, 2009
Printing Environment Variables Using Perl One Liner
Solution 1
C:\Documents and Settings\sivkumar>perl
use Data::Dumper;
print Dumper \%ENV;
Solution 2 - Perl One Liner
perl -MData::Dumper -e "print Dumper \%ENV"
Monday, July 6, 2009
Tilde-Tilde Operator
A bit obscure is the tilde-tilde "operator" which forces scalar context.
print ~~ localtime;
is the same as
print scalar localtime;
and different from
print localtime;
Spaceship Operator.
$a = 2 <=> 5; # $a is set to -1
$a = 5 <=> 2; # $a is set to 1
$a = 2 <=> 2; # $a is set to 0
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 there 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 thins 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 regexes
m xabcx
# same as m/abc/