I have a sub with some firmly variables and variables I declare and use within the sub, but when I call this sub I can't declare them.
for example:
sub func{
my ($firm1, $firm2, $possible) = @_;
...
if($possible eq "smth"){ # in case i passed this scalar
}
elsif($possible eq ("smth else" or undef/i_don_t_know)){ # in case i didn't passed this var, but i need it as at least undef or smth like that
}
func(bla, bla, bla); # ok
func(bla, bla); # not ok
When I tried that, I got an error
"Use of uninitialized value $possible in string eq at test.pl line ..."
How can I correct this?
This isn't a problem with declarations. If you pass only two parameters to a subroutine that begins with
my ( $firm1, $firm2, $possible ) = @_;
then $possible
is undefined, which means it is set to the special value undef
, which is like NULL
, None
, nil
etc. in other languages
As you have seen, you can't compare an undefined value without causing a warning message, and you must first used the defined
operator to check that a variable is defined
I think you want to test whether $possible
is both defined and set to the string smth
. You can do it this way
sub func {
my ( $firm1, $firm2, $possible ) = @_;
if ( defined $possible and $possible eq 'smth' ) {
# Do something
}
}
func( qw/ bla bla bla / ); # ok
func( qw/ bla bla / ); # now also ok