-1

I am using GetOptions to get values from perl

GetOptions(
       'lines=s'=>\$globallines,
        );

Here, lines is an optional argument. When the user does not enter a value, I am getting a use of uninitialized variable warning where I am using the lines variable in an if statement. I am unable to fix this warning. Can you please help him?

Sorry if it is a silly question,I am new to perl.

if($globallines>0){#<SOME CODEEE>
Sobrique
  • 52,974
  • 7
  • 60
  • 101
emma
  • 93
  • 1
  • 1
  • 10

2 Answers2

1

What's happening is - if there's no argument supplied, the value is undefined. (not zero).

So comparing it numerically gives an error.

There's a few possible solutions, but the easiest is:

if ( $globallines and $globallines > 0 ) { 

Or perhaps just initialise it if undefined:

$globallines //= 0; #sets it to zero if undef. 
Sobrique
  • 52,974
  • 7
  • 60
  • 101
  • Can I use <$globallines //= "name";> for a string value also?? – emma Jun 21 '17 at 13:18
  • Er. Yes. I think. But it's not `<` for code quotes, but backticks. But perl doesn't care. You can assign using `$globallines //= "a name here";` just the same as a numeric value. But your `>0` test will error still if you do this. (Unless the string is `"0.0"` or otherwise numerically convertible to zero) – Sobrique Jun 21 '17 at 15:10
1

If the -lines option is... er... optional(!), what do you want the behaviour to be when the option is omitted? Choose a default value and assign that before calling GetOptions().

my $globallines = 0; # Or whatever value is appropriate

GetOptions(
   'lines=s' => \$globallines,
);

Also, don't you want lines=i rather than lines=s? That will ensure you only get an integer.

Dave Cross
  • 68,119
  • 3
  • 51
  • 97