gpt4 book ai didi

perl - 如何在 Mojolicious::Lite 应用程序中使用我自己的子程序(全局)

转载 作者:行者123 更新时间:2023-12-04 06:37:56 24 4
gpt4 key购买 nike

我需要能够在 Mojolicious::Lite 应用程序中编写和调用我自己的子程序。但是,这样做的直观方法似乎不起作用。我给一位同事发了电子邮件,他对这个问题比我更有 Mojolicious 经验,他给我发送了以下代码:

#!/usr/bin/env perl
use Mojolicious::Lite;

# Documentation browser under "/perldoc"
plugin 'PODRenderer';

get '/' => sub {
my $self = shift;
$self->render('index');
};

sub factorial {
my $n = shift;
return $n ? $n * factorial($n - 1) : 1;
}

app->start;
__DATA__

@@ index.html.ep
% layout 'default';
% title 'Welcome';
Welcome to the Mojolicious real-time web framework!

Five factorial: <%= main::factorial(5) %>

@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= content %></body>
</html>

但是当我运行它时,它告诉我当我调用一个未定义的子程序时:

Undefined subroutine &main::factorial called at template index.html.ep from DATA section line 5, line 32.



我花了很多时间来处理这段代码,并尝试了不同的方法来让它工作,但到目前为止,唯一使它正常运行的是在@@ xxx.html 的范围内定义子例程。 ep的。我已经在 stackoverflow 上搜索/搜索了“Mojolicious::Lite 中的用户定义子程序”和其他类似的查询。似乎什么都没有出现。我对文档的搜索也被证明是徒劳的。这似乎应该是一项简单的任务,但我有点卡住了。任何帮助,将不胜感激。

最佳答案

正如 PerC 已经提到的,助手是向模板添加行为(或访问行为)的首选机制。由于他已经展示了该示例,因此我将补充说,您可以通过执行以下操作来混合两者(我正在删除 pod 渲染器插件,您不需要它)。

#!/usr/bin/env perl
use Mojolicious::Lite;

get '/' => sub {
my $self = shift;
$self->render('index');
};

sub factorial {
my $n = shift;
return $n ? $n * factorial($n - 1) : 1;
}

helper factorial => sub { shift; factorial(@_) };

app->start;
__DATA__

@@ index.html.ep
% layout 'default';
% title 'Welcome';
Welcome to the Mojolicious real-time web framework!

Five factorial: <%= factorial(5) %>

@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= content %></body>
</html>

关于perl - 如何在 Mojolicious::Lite 应用程序中使用我自己的子程序(全局),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22944341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com