在 Perl 中,如何将打印函数分配给变量?
in Perl, how to assign the print function to a variable?
我需要使用变量来控制打印方法
我的代码如下
#!/usr/bin/perl
# test_assign_func.pl
use strict;
use warnings;
sub echo {
my ($string) = @_;
print "from echo: $string\n\n";
}
my $myprint = \&echo;
$myprint->("hello");
$myprint = \&print;
$myprint->("world");
当我运行时,打印函数赋值出现如下错误
$ test_assign_func.pl
from echo: hello
Undefined subroutine &main::print called at test_assign_func.pl line 17.
看起来我需要在名称前加上前缀space 才能打印函数,但我找不到名称space。感谢您的任何建议!
CORE, some functions can't be called as subroutines, only as barewords. print中提到的就是其中之一。
print
是运算符,不是子运算符。
性能函数:
The functions in this section can serve as terms in an expression. They fall into two major categories: list operators and named unary operators.
Perl 为命名运算符提供了一个子项,可以由具有原型的子项复制。可以使用 \&CORE::name
.
获得对这些的引用
my $f = \&CORE::length;
say $f->("abc"); # 3
但是 print
不是这样的运算符(因为它接受文件句柄的方式)。对于这些,您需要创建一个具有更有限调用约定的子。
my $f = sub { print @_ };
$f->("abc\n");
相关:
- What are Perl built-in operators/functions?
我需要使用变量来控制打印方法
我的代码如下
#!/usr/bin/perl
# test_assign_func.pl
use strict;
use warnings;
sub echo {
my ($string) = @_;
print "from echo: $string\n\n";
}
my $myprint = \&echo;
$myprint->("hello");
$myprint = \&print;
$myprint->("world");
当我运行时,打印函数赋值出现如下错误
$ test_assign_func.pl
from echo: hello
Undefined subroutine &main::print called at test_assign_func.pl line 17.
看起来我需要在名称前加上前缀space 才能打印函数,但我找不到名称space。感谢您的任何建议!
CORE, some functions can't be called as subroutines, only as barewords. print中提到的就是其中之一。
print
是运算符,不是子运算符。
性能函数:
The functions in this section can serve as terms in an expression. They fall into two major categories: list operators and named unary operators.
Perl 为命名运算符提供了一个子项,可以由具有原型的子项复制。可以使用 \&CORE::name
.
my $f = \&CORE::length;
say $f->("abc"); # 3
但是 print
不是这样的运算符(因为它接受文件句柄的方式)。对于这些,您需要创建一个具有更有限调用约定的子。
my $f = sub { print @_ };
$f->("abc\n");
相关:
- What are Perl built-in operators/functions?