-1

我在子例程中有一个变量 currentUser 。它执行到一个子程序,但不执行到另一个子程序。如何在保持值的同时通过多个子例程传递变量?

sub login {
    &app_header;
    print <<EOF;
<form name="macform" method="POST" enctype="application/x-www-form-urlencoded"       action="$fullurl">
    ...stuff
    EOF  
}

sub html_menu {
    $me = $currentUser;
    print $me;
    print <<EOF;
    <form name="menuform" method="POST" enctype="application/x-www-form-urlencoded"     action="$fullurl">
    ..stuff
    EOF
    &app_list_button;
    print "<br>";
    &app_search_button;
    print "<br>";
    &app_edit_button;
    print "</div>";
}

当我尝试在 html_form 之后调用的新子中使用 html_form 子对 currentUser 执行相同操作时,该变量不会显示为用户在登录期间输入的内容。

4

3 回答 3

3
sub first {
    my $currentUser = shift;
    second($currentUser);
}

sub second {
    my $currentUser = shift;
    third($currentUser);
}

...等等。

将变量作为参数传递是通过@_变量完成的。您不应该尝试使用全局变量,这不是一个好方法。你可以这样做:

my ($arg1, $arg2, @rest) = @_;

或者通过使用shift,pop和其他操作数组的方法,就像我上面使用的shift.

如果您还没有这样做,我强烈建议您使用

use strict;
use warnings;

它将帮助您解决许多简单的问题。

于 2012-11-12T17:11:22.463 回答
2

最安全的方法是使用变量作为参数:

sub r1 {
    my $arg = shift;
    r2($arg);
}

sub r2 {
    my $arg = shift;
    print "$arg in r2\n";
}
于 2012-11-12T17:08:36.713 回答
1

当我尝试在 html_form 之后调用的新子中使用 html_form 子对 currentUser 执行相同操作时,该变量不会显示为用户在登录期间输入的内容。

首先,这是一个相当复杂的例子。您应该尝试将其分解。为了补充迄今为止其他人所说的内容,我将告诉您&子例程名称上的前缀,而不会()更改含义。您在示例中使用了它,我不确定您是否知道它的作用。所有这些都有略微不同的含义。

  • foo()foo这只是简单地调用不带参数的sub 。
  • &foo这调用了隐式foo传入。@_重要说明,如果通过引用进行foo修改,那么被调用者的也会改变。@_@_
  • &foo()这只是perl4的遗物。这foo使用显式的 subref sigil 调用。这在所有情况下都已弃用。

原型和印记也有细微的差异,&超出了问题的范围

有关更多信息,请参阅perldoc -q "calling a function"perldoc perlsub

于 2012-11-12T17:55:31.317 回答