Hold Subroutine response and set to variable in Pe

2019-09-01 10:29发布

问题:

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.