Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there other languages besides Perl with default variables?

Tags:

perl

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

like image 662
Danil Gaponov Avatar asked Jan 08 '23 22:01

Danil Gaponov


2 Answers

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;
     }
}
like image 119
Sobrique Avatar answered Feb 23 '23 15:02

Sobrique


Scala has something like $_, for example

List(1, 2, 3) map (_ + 2)

like image 24
Emil Perhinschi Avatar answered Feb 23 '23 15:02

Emil Perhinschi