Re:Perl 11
by mst on Wednesday October 24, 2018 @04:31AM
(#18290619)
Scoping - 'my' is lexical/block scoping, same as javascript's 'let' (thank you! steal more things please!) so
and note that if I e.g. typoed $count inside the subroutine I'd get a compile time error (and it goes out of scope at the end of the 'do { ... }' block). Note that the 'state' keyword provides an easier way to do this, but it's the easiest demo of closures I can think of, though also there's fun to be had with methods:
Constructor/accessor wise:
then means that
will throw an exception telling you foo is required
will work fine,
and (if you didn't pass a value for it to the constructor)
Hopefully that's a start, this is all typed off the top of my head on my first post-9am pint of coffee so my apologies for any omissions and/or errors.
[ Parent
| on HN ]
Also, in languages like Java, C++, or C#, you can use bare braces to define a new scope, no keyword necessary. It's not done so much anymore because modern coding standards tend to favor shorter functions for clarity and unit testability, but it's always still an option.
You can do bare braces in perl5 too, I used the 'do { ... }' block because that's an expression rather than a statement so I could return the subroutine -
my $code;
{
my $count = 0;
$code = sub { ++$count };
}
would've been equivalent but I always try and do assign-once-at-declaration-time where possible because mutable state is my mortal enemy.what's the js equivalent to your example?
let code = () => {
let count = 0;
return ++count
}
doesn't do the trick