in reply to Is it possible to use a scalar to call a subroutine?
#!/usr/bin/perl use strict; use warnings; my $sub = 'do_this'; { no strict "refs"; print $sub->("Fred"); } sub do_this { my $var = shift; return "My name is $var"; } sub do_that { my $var = shift; return "My name is not $var"; } __END__ My name is Fred
And with a dispatch table, which leaves strict intact:
#!/usr/bin/perl use strict; use warnings; my %dispatch_table = ( do_this => sub { my $var = shift; return "My name is $var"; }, do_that => sub { my $var = shift; return "My name is not $var"; }, ); my $sub_name = 'do_this'; print $dispatch_table{$sub_name}("Fred"); __END__ My name is Fred
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Is it possible to use a scalar to call a subroutine?
by JavaFan (Canon) on May 06, 2010 at 17:32 UTC | |
by kennethk (Abbot) on May 06, 2010 at 17:39 UTC | |
Re^2: Is it possible to use a scalar to call a subroutine?
by bradcathey (Prior) on May 06, 2010 at 18:32 UTC |