in reply to Comparing references to sub's

mmmm... so your lower level sub tells you which function to call, but at a higher level you want to know which one it chose, so you can do some other stuff?

Perhaps it would be better to code it using sub NAMES rather than refs?

#!/usr/local/bin/perl -w use strict; no strict qw(refs); my $food = $ARGV[0]; $food ||= 'apple'; my $subname = choose($food); print "We got '$subname' - let's get cookin!\n"; &$subname($food); if ( $subname eq 'fruit' ) { print "Puddings up!\n"; } #--------------- sub choose { my $food = shift; return 'fruit' if ( $food eq 'apple' ); return 'vege' if ( $food eq 'carrot' ); return 'unknown'; } sub fruit { my $food = shift; print "I think '$food' is FRUIT!\n"; } sub vege { my $food = shift; print "I think '$food' is VEGE!\n"; } sub unknown { my $food = shift; print "I don't think '$food' is food at all!\n"; }

Then you are working with sub names, and it is clear in your code when you say thinks like:

if ( $subname eq 'do_zipped_things' )...

My 0.02 dollars, regards Jeff

Replies are listed 'Best First'.
Re: Re: Comparing references to sub's
by leriksen (Curate) on Mar 24, 2003 at 03:41 UTC

    yes , and my first attempt at this was be using strings and interpolating them as function names - was quite useful during debugging etc. But I wanted to use refs from the 'purity' aspect - I didn't want to use a name that represented a function. I also _think_ it is a 'better way' from the prespective of speed/efficiency (moderately better).

    As for

     if ( $subname eq 'do_zipped_things' )...

    being clearer, isn't

     if ( $ref ==  \&desired_code )...

    just as clear. Refs are even better though, because you are checking that your reference really does 'point' to existing code - the string way, you have a string that 'might' also be the name of a subroutine. How do you check that the string can be 'called'?

    But the really important point, that I think has been missed, is when does equating ref's to subroutines _not_ work e.g what about in anonymous namespaces, or equating methods in objects/classses, what if someone does something weird with gensym(), or plays around with the CODE entry in symbol tables, does the sub have to be exported some how from a module etc, etc