3 ms·
There are useful cases for this. It's much less ambiguous in those cases if your language allows the definition of the variable in the same location, and scope
by kbenson 10y ago
There are useful cases for this. It's much less ambiguous in those cases if your language allows the definition of the variable in the same location, and scopes it. For example, Perl:
use strict;
use warnings;
sub one { 1 }
if ( my $one = one() ) {
say $one; # prints 1
}
say $one; # compilation error, "Global symbol "$one" requires explicit package name"
This case is trivial, but when you want a temporary variable and don't want to clutter your scope, it can be useful.
That's not to say assignment and equivalence might not be better off with different operators, as noted by others here.
- dbaupp 10y agoDeclaration and a (mutating) assignment are different: your example demonstrates that Perl signals the declaration with `my`, and other languages offer similar things like `if let ... = ... { ... }`
- kbenson 10y ago> Declaration and a (mutating) assignment are different Yes, that's what I was trying to get at by saying definition, but not very clearly. It's one of the reasons I prefer languages to require and clearly indicate variable declaration in most cases.