Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
179 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...