[Melbourne-pm] Postfix conditionals and creating lexicals

Adam MacLeod adam at macleod.id.au
Wed Jul 11 16:33:15 PDT 2012


Hey Guys,

I showed this behaviour to a work colleague, and he came up with the
following:

-- 8< --

#!/usr/bin/perl

use strict;
use warnings;

sub foo {
  my $baz = 0 if 0;
  $baz ||= 0;
  print "baz = $baz\n";

  $baz += 10;
}

sub bar {
  my $baz = 0 if 0;
  $baz ||= 0;
  print "baz = $baz\n";

  $baz += 100;
}

foo;
bar;
foo;
bar;
foo;
bar;
foo;
bar;

-- >8 --

$baz isn't global, but it persists locally between calls. Does anyone know
exactly what is happening here? I'm relatively new to Perl and might just
be missing something easy :)

Cheers,
Adam

On Thu, Jul 12, 2012 at 9:00 AM, Alfie John <alfiej at opera.com> wrote:

> Hi guys,
>
> Thanks to Rob Norris for reminding me to bring up my rant on Google+
>
> What do people think about the following?
>
> -- 8< --
>
> #!/usr/bin/perl
>
> use strict;
> use warnings;
>
> sub foo {
>   my ( $bar ) =@_;
>
>   my $baz = $bar if $bar;
>   print "baz = $baz\n";
>
>   $baz = 42;
> }
>
> foo( 1 );
> foo( 1 );
> foo( 0 );
> foo( 0 );
>
> -- >8 --
>
> Alfie
>
> --
>   Alfie John
>   alfiej at opera.com
> _______________________________________________
> Melbourne-pm mailing list
> Melbourne-pm at pm.org
> http://mail.pm.org/mailman/listinfo/melbourne-pm
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/melbourne-pm/attachments/20120712/d8584114/attachment.html>


More information about the Melbourne-pm mailing list