Search code examples
perlvariablessubroutine

Hold Subroutine response and set to variable in Perl


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.


Solution

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