0

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?

3
  • 1
    Your question has nothing to do with declarations. Commented Jan 13, 2017 at 12:54
  • It would help a lot if you showed code that is compilable under use strict and use warnings. Commented Jan 13, 2017 at 13:45
  • It would help a lot if you showed code that will compile under use strict and use warnings. Making up stuff that isn't even Perl code makes your question far too ambiguous. Commented Jan 13, 2017 at 15:54

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that's almost exact what i need
2

It's not a problem with a declaration, but rather passing an undefined value.

There's several ways of handling this:

  • Test for defined on the variable
  • Set a 'default' $possible //= "default_value" will conditionally assign if undefined.

Or do something else entirely.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.