Search code examples
perlfunctionsubroutine

How to create a dynamic subroutine name in perl


I want to create a dynamic subroutine name in perl, Here is trial code , I am getting error "Bad name after feed_load::"

#!/usr/bin/perl
use strict;
use warnings;

BEGIN {
      push @INC, '/freespace/attlas/data/bin/genericLoader /FeedLoaderLib/'
}

use feed_load;
my type ="L";
my $tempTablefunct  = "Create".$type."Temp_Table";

feed_load::&$tempTablefunct->($tablename); ### pass a dynamic sub name HERE ###

Solution

  • &{ $pkg_name."::".$sub_name }( @args )
    

    or

    ( $pkg_name."::".$sub_name )->( @args )
    

    These will fail, however, because you asked Perl to forbid you from doing this by placing use strict; in your program. You can disable use strict; locally.[1]

    my $ref = do { no strict 'refs'; \&{ $pkg_name."::".$sub_name } };
    $ref->( @args )
    

    But it turns out that \&$sub_name is already exempt from strictures, so you simply need the following:

    my $ref = \&{ $pkg_name."::".$sub_name };
    $ref->( @args )
    

    If instead of sub call you need a method call, you can use

    my $ref = $o->can( $method_name );
    $o->$ref( @args )
    

    or just

    $o->$method_name( @args )
    

    1. It's sensible to ask Perl to prevent the use of symbolic references, because it's easy to use one by accident. But here we intend to use a symbolic reference, so it's also sensible to disable strictures where the symbolic reference is used.