Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I was using this code to fetch a CGI parameter:

$page = int(param('page'));

This sometimes results in:

warning: Use of uninitialized value in int

Is this a good solution to resolve this warning, or is better and more succinct code available?

if (defined param('page')) {
    $param_page = int(param('page'));
} else {
    $param_page = 1;
}
share|improve this question
    
What is the param function? – 200_success Jun 15 '16 at 20:50
    
I have use CGI qw/:standard/ at the top of my script which imports the param() function. param() gets a value from the query string. – Leo Galleguillos Jun 15 '16 at 20:53
up vote 5 down vote accepted

Standard practice is to scope variables using my.

Since Perl 5.10, the preferred way to write this is to use the logical defined-or operator to provide a default value when undef is encountered.

my $param_page = int(param('page') // 1);
share|improve this answer
    
I have not seen // before. Thank you! – Leo Galleguillos Jun 15 '16 at 21:02
2  
By the way, if you think you should interpret an erroneous "0" parameter value as page 1, then you should use the || operator instead. – 200_success Jun 15 '16 at 21:05
    
Makes sense. Thank you. – Leo Galleguillos Jun 15 '16 at 21:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.