in reply to difference between 'if (condition) { expression;}' and 'expression if (condition)'

Scope.

In your first example, $var is declared inside the if block, but exists ONLY within that block. Since it's undefined when program_flow encounters the print statement, strict pumps out the error.

On the other hand, in your example 2, "my $var" is in scope throughout the code you show.

  • Comment on Re: difference between 'if (condition) { expression;}' and 'expression if (condition)'

Replies are listed 'Best First'.
Re^2: difference between 'if (condition) { expression;}' and 'expression if (condition)'
by xdg (Monsignor) on Mar 22, 2006 at 14:37 UTC

    Careful with my $var if $condition. From perlsyn:

    NOTE: The behaviour of a "my" statement modified with a statement modifier conditional or loop construct (e.g. "my $x if ...") is undefined. The value of the "my" variable may be "undef", any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons.

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

      Thanks xdg. I won't use. I saw something similar in an existing code and I was surprised that it works. Hence I decided to prod a bit.
      Regards,
      Ranjan
Re^2: difference between 'if (condition) { expression;}' and 'expression if (condition)'
by diotalevi (Canon) on Mar 22, 2006 at 14:36 UTC

    The second example is also buggy and shouldn't be used. Declare the variable in the previous line. The bug is that the runtime effect of my() is avoided when the condition fails.

    my $var; $var = 'ok' if @_;

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

Re^2: difference between 'if (condition) { expression;}' and 'expression if (condition)'
by ranjan_jajodia (Monk) on Mar 22, 2006 at 14:38 UTC
    Thanks ww.
    Since the second example works fine which means that even though the expression is not executed because of the condition being false, still the variable is declared. Is it like the perl interpreter first parses the code for the declared variables and their scope and then starts executing the code?
    Regards,
    Ranjan