保持子程序响应并在 Perl 中设置为变量 [英] Hold Subroutine response and set to variable in Perl

查看:42
本文介绍了保持子程序响应并在 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();

这篇关于保持子程序响应并在 Perl 中设置为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆