1

我收到此错误,无法理解为什么会发生这种情况。当我跳转到另一个子程序时会发生这种情况。也许我需要了解 Mojolicious 发生这种情况的原因。

这是我的程序的源代码:

#!/usr/bin/perl

use Mojolicious::Lite;

get '/' => sub { &start_home; };

app->start;

sub start_home {
  my $d = shift;
  my $something = $d->param('something');
  ### Do things with $something.... etc.. etc..
  &go_somewhere_else; ### Go somewhere else
}

sub go_somewhere_else {
 my $c = shift;
 $c->render(text => "Hello World!");
 ### End of program
}

我将一个值传递给渲染器并且有一个值 - 为什么它会说它是未定义的?我的理解是,只有当您跳转到子程序并尝试渲染输出时才会发生这种情况。

我的操作系统是 Windows,我使用的是 Strawberry Perl。

4

1 回答 1

3

您需要将上下文对象$c/传递$d给您的第二个函数。未定义的值是您的$cin go_somewhere_else,因为您在没有参数的情况下调用它。

最初,要使其工作,请执行此操作。

sub start_home {
  my $d = shift;
  my $something = $d->param('something');

  go_somewhere_else($d);
}

您现在将您命名的上下文$d(这不是常规名称)传递给另一个函数,并且警告将消失。

那是因为不带括号的形式(&subname;即函数的参数列表)在 内部可用,但因为你ed关闭,现在是空的,因此你的内部是.()@_go_somewhere_elseshift$d@_$cgo_somewhere_elseundef

或者,您也可以使用 将 更改shift为分配@_。但请不要那样做

sub start_home {
  my ( $d ) = @_;
  my $something = $d->param('something');

  &go_somewhere_else;
}

这里还有更多奇怪到几乎是错误的事情。

get '/' => sub { &start_home; };

您正在对函数进行柯里start_home化,但实际上并没有添加另一个参数。我在上面解释了为什么这样做。但这不是很好。事实上,它令人困惑和复杂。

相反,您应该对路线使用代码参考。

get '/' => \&start_home;

在里面start_home,你应该$c按照惯例调用你的上下文。您也不应该使用 &&符号来调用函数。这会以您最不希望的方式改变行为。

sub start_home {
  my $c = shift;
  my $something = $c->param('something');

  # ...
  go_somewhere_else($c);
}

要了解有关函数调用如何在 Perl 中工作的更多信息,请参阅perlsub

于 2016-09-23T15:01:37.370 回答