So I tried this using the following code, where %format_conv has an
entry for each type of conversion needed with a list of items:

   foreach my $fmtcnv (sort keys %format_conv)
   {
      my @itemlist= @{$format_conv{$fmtcnv}};  #List of items

      print "\nFormat conversion: '$fmtcnv'\n\t", scalar(@itemlist), "
items: ", join(" ", @itemlist), "\n";

      my $subname= "formatconv_".$fmtcnv;  #Sub name
      unless (defined &{$subname})  #Check if sub is defined
      { print "*ERR: Format conversion sub $subname not defined"; next;
}

      map { &{$subname}($_) } @itemlist;  #Convert all the items
   }

When I run it, the 'defined' part works fine, but I get an error on the
last line:

Can't use string ("formatconv_bidir2in") as a subroutine ref while
"strict refs" in use at bsdl_gen.pl line 238.


How do I get this sub call to work with the sub name in a variable?
Thanks,

-Nilanjan


-----Original Message-----
From: Ronald J Kimball [mailto:[EMAIL PROTECTED] 
Sent: Monday, September 10, 2007 3:01 PM
To: Palit, Nilanjan
Cc: [email protected]
Subject: Re: [Boston.pm] Subroutine definition

On Mon, Sep 10, 2007 at 11:51:56AM -0700, Palit, Nilanjan wrote:
> I have to do some format conversions, so I'm defining subroutines like
> "sub FormatConv_X2Y()". At this point I have only a few of the format
> conversions defined & I haven't gone through the entire dataset to
know
> all the format conversions needed. So I'd like to check whether a
> specific format conversion subroutine is defined before I call it (all
> the subroutine names will be of the form "FormatConv_X2Y") -- is there
a
> way to do that? In other words, is there a way to find out whether a
> subroutine is defined before calling it?

Yes, you can do C<defined &FormatConv_X2Y>, with that exact syntax; an
ampersand and no parentheses.

Other options include:

Creating a converter object, and doing
C<$converter->can('FormatConv_X2Y')>.

Storing the subroutines in a hash, and doing
C<exists $format_converters{'X2Y'}>.

Ronald
 
_______________________________________________
Boston-pm mailing list
[email protected]
http://mail.pm.org/mailman/listinfo/boston-pm

Reply via email to