http://www.perlmonks.org?node_id=495983


in reply to Re^4: Have you netted a Perl Monk or Perl Pretender in 5 minutes or less?
in thread Have you netted a Perl Monk or Perl Pretender in 5 minutes or less?

It tests the candidate's understanding of Perl syntax. To understand that line you must know the effects of using unless (and if I'm asking the questions that will quickly turn into what Perl considers true and false values) as well as execution order in a statement. Put concicely, it says that if $c exists and is true maintain it's value, otherwise set it to 1. It is an occasionally useful construct for fixing user input errors and the like.

I did notice that the way you've got it written it is a trick question - if you set the original value of $c to be 0 or "" the "my" would produce a warning about re-declaring a variable that was declared in the same scope.
  • Comment on Re^5: Have you netted a Perl Monk or Perl Pretender in 5 minutes or less?

Replies are listed 'Best First'.
Re^6: Have you netted a Perl Monk or Perl Pretender in 5 minutes or less?
by Anonymous Monk on Sep 29, 2005 at 15:37 UTC
    To understand that line you must know the effects of using unless (and if I'm asking the questions that will quickly turn into what Perl considers true and false values) as well as execution order in a statement. Put concicely, it says that if $c exists and is true maintain it's value, otherwise set it to 1.
    Wrong. It is an anomoly caused by the interaction between lexical scopes created by "my" and postfix conditionals. To put it correctly, if $c is false, then set it to one. If $c is true then set it to undef. If you actually try running that snippet you'll learn what it really does.
      Correct you are, my bad. I'm used to calling that in a different context so I looked back at the code I had actually been using. This is what would actually work the way I described:
      use strict; use warnings; my $c = 1; my $d = undef; sub sbr { $c = 2 unless $c; print "c = $c\n"; $d = 4 unless $d; print "d = $d\n"; } sbr();


      Thanks for correcting my mistake