Home: Perl Programming Help: Beginner:
accessing subs from variables



goli123
New User

Mar 15, 2013, 5:49 PM


Views: 788
accessing subs from variables

hi everybody, I'm new around here :)
I have a problem with a new program that I'm writing.
I'll show you the code and than explain the problem.

this is my code:

Code
use strict; 

my $input;
my %h;
$h{show} = \&show;


while (1>0)
{
$input = <STDIN>;
$h{$input}->();
}

sub show()
{
printf "bla";
}


When I'm running it i get the following error (in the STDIN part I'm typing "show"):
"Can't use string ("") as a subroutine ref while "strict refs" in use at file.pl line 12, <STDIN> line 1."
after some reading i think that the problem is in the line "$h{$input}->();" there some how my variable become null.
i hope you could help me get this program up and running :)


Kenosis
User

Mar 15, 2013, 5:54 PM


Views: 785
Re: [goli123] accessing subs from variables

Did you mean:

Code
use strict; 
use warnings;

my $input;
my %h;
$h{show} = \&show;

while (1) {
chomp( $input = <STDIN> );
$h{$input}->();
}

sub show() {
printf "bla";
}


Remember that you need to chomp off the newline... Here's what's happening:

Code
Use of uninitialized value in subroutine entry at temp3.pl line 10, <STDIN> line 1. 
Can't use string ("") as a subroutine ref while "strict refs" in use at temp3.pl line 10, <STDIN> line 1.


Without the chomp when you enter "show" you're using $h{"show\n"} , but that's associated with an "uninitialized value." Next, Perl was expecting a sub reference, but the associated value was "", and so Perl complained.


(This post was edited by Kenosis on Mar 15, 2013, 6:08 PM)


goli123
New User

Mar 15, 2013, 6:05 PM


Views: 779
Re: [Kenosis] accessing subs from variables

thanks, works :)