Hold Subroutine response and set to variable in Perl

醉酒当歌 提交于 2019-12-25 03:13:59

问题


My code:

#!/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 print nothing, I want to print hello. I have intent to change thesub() to \&thesub, but not work.

I read that In Perl, scalar variables cannot hold subroutines directly.

How can I fixed this case ?

Thanks.


回答1:


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();



回答2:


You are passing one parameter into thesub(), but it expects two. So "hello" ends up in $class and $self ends up containing nothing (or, more precisely, undef). The easiest fix is to remove the line which assigns to $class. But I'm not sure if that's the best fix as I'm pretty unclear on what you're actually trying to do here.

The variable names ($class, $self) make me think you're reading a tutorial about object-oriented programming. But there's no OO going on here.

Also, I can't think of a situation in OO Perl where you'd pass both $class and $self to a methd.



来源:https://stackoverflow.com/questions/49791034/hold-subroutine-response-and-set-to-variable-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!