2
\$\begingroup\$

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;
}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jun 15, 2016 at 20:44
\$\endgroup\$
2
  • \$\begingroup\$ What is the param function? \$\endgroup\$ Commented Jun 15, 2016 at 20:50
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Jun 15, 2016 at 20:53

1 Answer 1

5
\$\begingroup\$

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);
answered Jun 15, 2016 at 20:59
\$\endgroup\$
1
  • 2
    \$\begingroup\$ By the way, if you think you should interpret an erroneous "0" parameter value as page 1, then you should use the || operator instead. \$\endgroup\$ Commented Jun 15, 2016 at 21:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.