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?

ChrisM
  • 1,576
  • 6
  • 18
  • 29
genesi5
  • 455
  • 3
  • 17
  • 1
    Your question has nothing to do with declarations. – melpomene Jan 13 '17 at 12:54
  • It would help a lot if you showed code that is compilable under `use strict` and `use warnings`. – Borodin Jan 13 '17 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. – Borodin Jan 13 '17 at 15:54

2 Answers2

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
Borodin
  • 126,100
  • 9
  • 70
  • 144
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.

Sobrique
  • 52,974
  • 7
  • 60
  • 101