in reply to strange scope
are the two blocks part of the same "virtual" code block?They are in the same scope as Zaxo explains. You can also ask Perl for more help by using diagnostics:
would say:#!/usr/bin/perl use strict; use warnings; use diagnostics; if (my $x = 1) { # } elsif (my $x = 2) { # }
"my" variable $x masks earlier declaration in same scope at test.pl li +ne 9 (#1) (W misc) A "my" or "our" variable has been redeclared in th +e current scope or statement, effectively eliminating all access to t +he previous instance. This is almost always a typographical error. +Note that the earlier variable will still exist until the end of the +scope or until all closure referents to it are destroyed. Found = in conditional, should be == at test.pl line 9 (#2) (W syntax) You said if ($foo = 123) when you meant if ($foo == 123) (or something like that).
But there's something else. If that's what you really have in your code, you get another warning as liverpole said about Found = in conditional as you can see from the output above. Why? Simple assignment like $x = 'some_value' would always evaluate to true or false (depending the value of 'some_value'). However, if you assign from an expression such as calling a function, then it would be taken as you assign a variable and want to evaluate that variable at once. Consider this:
would print 3 without any warnings. I use this construct very often to firstly save a value from a function calling to proceed it further only if it's true. And I keep the variable from visible out of the scope since the variable would be irrelevant for the rest of the code.#!/usr/bin/perl use strict; use warnings; use diagnostics; # set $x from get_num(), if it returns true value # then do something with $x if (my $x = get_num()) { print $x, "\n"; } else { print "empty\n"; } sub get_num { 3 }
If you instead, want to test beyond true or false of a variable, you could say for example:
but I think it's too much noise. I would instead write something similiar to Herkum's code:if ( (my $x = get_num()) >= 3 ) { ... }
So, basically, be clear about what you want to do and what result you expect.my $x = get_num(); # assumed to always returns a number if ($x < 0 ) { # negative numbers } elsif ($x < 3) { # less } else { # OK }
Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!
|
|---|