Question

I'm writing a Mason 1.x component page, and it's not behaving like I'm expecting. The perlsub man page indicates that a my variable should be accessible inside a sub. But the following code:

my @myOrderBy = @orderBy;
sub sortAll
{
  my $ret = 0;
  foreach my $sortStr (@myOrderBy)
  {
  }
}

Is giving me the error:

Error during compilation of /opt/rt4/local/plugins/RTx-Foo/html/cf/helpers/ticketQuery.ajx: Variable "@myOrderBy" is not available at /opt/rt4/local/plugins/RTx-Foo/html/cf/helpers/ticketQuery.ajx line 206.

(line 206 is the foreach line)

The same code works fine in a non-Mason context.

Was it helpful?

Solution

Mason apparently wraps your code in a sub (like mod_perl does). That means you end up with something like

$ perl -we'sub { my $x; sub sortAll { $x } }'
Variable "$x" is not available at -e line 1.

The explanation is long as complicated, but it boils down to: Perl doesn't support nested named subs. Attempting to do so leads to weird errors.

Might I suggest you use local our $x; instead of my $x; in this situation?

OTHER TIPS

You shouldn't be using named subs in Mason components, the namespace is shared. Use this instead:

my $sortall = sub { ... };

my variables are visible only within the code block they're declared in. The sub is a different code block, and therefore @myOrderBy is not available within it. See http://www.perlmonks.org/index.pl?node_id=66677

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top