I have recently learnt about Perl's default variable $_
. A good article on topic is here http://perlmaven.com/the-default-variable-of-perl. I find the ability to apply functions to it without specifying the argument fascinating. Are there any other programming languages with similar facilities?
EDIT: Some of the languages listed in comments are:
Powershell - should be very similar to Perl.
Groovy - has generic it
iterator variable.
Scala - has _
variable as generic lambda argument.
Lisp - has anaphoric macros.
HyperTalk and AppleScript - see @AmbroseChapel answer
I'd suggest rather than looking for a "default" variable, instead you consider it in terms of implicit variables. Those are rather more common.
If you look for example, at awk
sed
grep
etc. - they apply their magic to 'the current line'.
E.g.
sed -e 's/fish/paste/g' myfile
Will implicitly iterate myfile, and apply the pattern once per line.
I think this is whence it came in perl - because perl lets you emulate sed:
perl -p -e 's/fish/paste/g' myfile
If you deparse this, you turn it into:
LINE: while ( defined ( $_ = <ARGV> ) ) {
s/fish/paste/g;
}
continue {
die "-p destination: $!\n" unless print $!;
}
Perl's just being a bit more ... explicit about it's implicitness. I mean, once you start 'setting' an implicit variable in a while
loop, then from there it makes sense to do so in a for
loop.
I would urge caution though - I like $_
but I don't like writing it - I feel that if I actually am, then I'd usually be better off with naming a variable instead.
As always with programming - and especially with perl
- readability and clarity is king.
I think being able to write;
my $regex = qr/some_pattern/;
while ( <STDIN> ) {
print if m/$regex/;
}
Is clearer than:
while ( my $line = <STDIN> ) {
if ( $line =~ m/some_pattern/ ) {
print $line;
}
}
Scala has something like $_, for example
List(1, 2, 3) map (_ + 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With