% %p = ('option1' => 'Option 1',
% 'option2' => 'Option 2',
% 'option3' => 'Option 3'
% );
<select name="killer_feature" id="killer_feature" class="select">
% foreach (keys %p) {
% my $selected = param('killer_feature') && param('killer_feature') eq $_ ? 'selected="selected"' : '';
% if (!param('killer_feature') && $_ eq 'option2') { $selected = 'selected="selected"' }
<option value=" <%=$_%>" <%= $selected %>>
<%= $p{$_} %>
</option>
% }
</select>
the above code breaks the app by returning ‘Internal server error’, but if I smiply edit the very first line to % my %p (I tried it because some other controls have this format) it works, I wonder whats the difference between the two.
Its a perl app built on Mojolicious web framework.
Many thanks!
Raw
%psays to use a global (package) variable “%p”. To be more technical, by default, a non-declared variable name is considered to be a package variable and is silently pre-pended with the name of the current package – e.g. it would be really referring to%main::pvariable since you’re in the main package by default.BUT If the Perl code is run by the interpreter with the
use strictpragma enabled (as it is with mojo), this automatic pre-pending of a current package name to un-declared variables does not happen, and therefore the code with such a variable will not compile as the variable%pis not actually known from either a lexical scope declaration or package symbol table.Adding
mydeclares the “%p” variable into a local (lexical) scope and it will now happily satisfy thestrictpragma.A much more in-depth (and better written) explanation of variable scoping in Perl is avialable from Randal Schwartz’s Stonehendge consulting web site: http://www.stonehenge.com/merlyn/UnixReview/col46.html