Skip to content

Instantly share code, notes, and snippets.

@Gro-Tsen
Created April 15, 2022 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gro-Tsen/87fae2262cc7c028bba664903bff906b to your computer and use it in GitHub Desktop.
Save Gro-Tsen/87fae2262cc7c028bba664903bff906b to your computer and use it in GitHub Desktop.
#! /usr/local/bin/perl -w
use strict;
use warnings;
for ( my $i=0 ; $i<5 ; $i++ ) {
my $var;
sub returnvar { return $var; }
$var = $i;
print "\$i=$i, \$var=$var, returnvar returns ", returnvar, "\n";
}
@dwyart
Copy link

dwyart commented Apr 15, 2022

my sub returnvar { return $var; }
will work

@dseddah
Copy link

dseddah commented Apr 15, 2022

your line 5 statement reinitialize $var at 0 on every iteration of the for loop. just move it before the for.
what you want would require a "static" pragma like in C (static int foo;)

@Gro-Tsen
Copy link
Author

my sub returnvar { return $var; } will work

Thanks! That's what I was looking for.

@dseddah
Copy link

dseddah commented Apr 15, 2022

i'm totally baffled by this :(

@dwyart
Copy link

dwyart commented Apr 15, 2022

This has been discussed in Perl circles for more than 20 years...

@Gro-Tsen
Copy link
Author

This has been discussed in Perl circles for more than 20 years...

20 years is actually surprisingly recent given that lexical scoping has been standard and well-known since ALGOL-60 and was the major change between Lisp 1 and Lisp 1.5 in 1962. 😝

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment