imcsk8 has asked for the wisdom of the Perl Monks concerning the following question:

i have the following working code
my %ext = ('jpg' => 'jpeg', 'jpeg' => 'jpeg', 'png' => png', 'JPEG' => 'jpeg', ,'JPG' => 'jpeg', 'PNG' => 'png'); .... my $aux = $ext{'JPEG'}; print $image->$aux(); ...
but there is something that i don't understand; why when i use $image->$ext{'JPEG'} does not work???
isn't $ext{'JPEG'} a scalar value and should work the same as $aux??

thanks for the comments.

ignorance, the plague is everywhere
--guttermouth

Replies are listed 'Best First'.
Re: subroutine referencing
by broquaint (Abbot) on Mar 09, 2004 at 18:04 UTC
    The parser expects a bareword or a simple scalar for the method name. The idiomatic approach is to use a scalar dereference operation when dealing with more syntactically complex scalars e.g
    print $image->${ \$ext{JPEG} };
    HTH

    _________
    broquaint

      i was thinking something like that but i still had my doubts. thanks!!

      ignorance, the plague is everywhere
      --guttermouth
Re: subroutine referencing
by dragonchild (Archbishop) on Mar 09, 2004 at 19:20 UTC
    In the spirit of TMTOWTDI, I would use the following idiom:
    my %ext = ( ... ); ... my $method = $ext{'JPEG'}; print $image->$method; ...

    That makes it clearer what the point of the variable is - it's a method name.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

      for the sake of clarity, i left the code like that because i sent it to a non-perl programmer and the other way could be kind of obscure for him


      ignorance, the plague is everywhere
      --guttermouth
Re: subroutine referencing
by cyocum (Curate) on Mar 10, 2004 at 13:15 UTC

    I was looking at your code and it is pretty megre so disregard this if it is not what I think. Could you use AUTOLOAD on your $image object then use a regex to normalize the sub call to your calling convention then call the function or something along those lines rather than having a hash with all the possible variations in it?

    Just a thought.

      I'm assuming that the OP is using either GD or ImageMagick, so the answer would most likely be no.

      Also, the technique is very useful in other situations. What the OP has is very similar to a dispatch table, but is a list of method names, not subroutine references.

      ------
      We are the carpenters and bricklayers of the Information Age.

      Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.