"my" variable $id masks earlier declaration in same scope
if ( my $id = $obj->get_id() )
{
$obj->do_this();
}
elsif ( my $id = $obj->create_id() )
{
$obj->do_that();
}
else
{
$obj->do_somethingelse();
}
a quick fix was to replace it with this:
my $id ;
if ( $id = $obj->get_id() )
{
$obj->do_this();
}
elsif ( $id = $obj->create_id() )
{
$obj->do_that();
}
else
{
$obj->do_somethingelse();
}
however, i'm wonderng if there's another way.
if ( $_ = $obj->get_id() )
{
# use $_ inside this block...
$obj->do_this();
}
elsif ( $_ = $obj->create_id() )
{
# use $_ inside this block
$obj->do_that();
}
else
{
$obj->do_somethingelse();
}
Generally, however, this wouldn't be a very sound approach, as it is usually very easy to loose track of the $_ variable. Although, it does spare you having to declare variables, especially for short code blocks or loops.
if ( local $_ = $obj->get_id() )
{
# use $_ inside this block...
$obj->do_this();
}
elsif ( $_ = $obj->create_id() )
{
# use $_ inside this block
$obj->do_that();
}
else
{
$obj->do_somethingelse();
}
You're getting the error because all the if and elsif expressions execute in the same scope (which starts with the if and ends with the last 'then', elsif or else clause). You just need to remove the second my since the first one is still in effect.
if ( my $id = $obj->get_id() )
{
$obj->do_this();
}
elsif ( $id = $obj->create_id() )
{
$obj->do_that();
}
else
{
$obj->do_somethingelse();
}
However, I find the lack of symetry weird, so I would probably take the my $id; outside of the if.
{ ### Do this or that for $obj
my $id;
if ( $id = $obj->get_id() ) {
$obj->do_this();
} elsif ( $id = $obj->create_id() ) {
$obj->do_that();
} else {
$obj->do_somethingelse();
};
};
{ ### Do this and that for $next_obj
my $id;
if ( $id = $next_obj->get_id() ) {
$next_obj->do_this();
} elsif ( $id = $next_obj->create_id() ) {
$next_obj->do_that();
} else {
$next_obj->do_somethingelse();
};
};
perlmonks.org content © perlmonks.org and Anonymous Monk, ikegami, nmerriweather, vladb
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03