保持子程序响应并在 Perl 中设置为变量
问题描述:
我的代码:
#!/usr/bin/perl
use strict;
use warnings;
thesub("hello");
sub thesub {
my $class = shift;
my $self = shift;
return $self;
}
my $testvar = thesub();
print $testvar;
$testvar 什么都不打印,我想打印 hello.我打算将 thesub() 更改为 \&thesub,但不起作用.
$testvar print nothing, I want to print hello. I have intent to change thesub() to \&thesub, but not work.
我读到在 Perl 中,标量变量不能直接保存子例程.
I read that In Perl, scalar variables cannot hold subroutines directly.
我该如何解决这个问题?
How can I fixed this case ?
谢谢.
答
你没有包,所以我假设你不想使用类,
You don't have package, so I'll assume you don't want to use a class,
use strict;
use warnings;
use v5.10;
sub thesub {
state $stored;
$stored = shift if @_;
return $stored;
}
thesub("hello");
print thesub();