I was just reading How to delete a file with a print statement, which mentions that the key in a hash is evaluated as code when the hash is interpoloated. I had the sudden inspiration that this might be a way to clean up (slightly) the ugliness of method interpolation.

For example, if you have an object $foo, and you want to print one of its attributes you can choose one of the following approaches:

my $attr = $foo->attr; print "Attribute is $attr\n"; print "Attribute is ". $foo->attr ."\n"; print "Attribute is @{[$foo->attr]}\n";

In my opinion all of these options leave somthing to be desired.

My inspiration was that, since a hash key is evaluated, why not just use a tied hash that does nothing but returns the key. So $foo{'a value' will return 'a value'. I'm not sure about the wisdom of this move, but it seems to make the syntax a little cleaner.

Any thoughts on whether this sort of thing is a good idea? Or, perhaps, retched and foolish?

use strict; use warnings; # Create a dummy class use Class::Struct Foo => [ attr => '$' ]; # with a dummy method sub Foo::Repeater { my $self = shift; my $times = shift || 1; return ($self->attr) x $times; # Make sure x operates in list con +text } # Create a dummy object my $foo = Foo->new(attr => 'foo'); # Create my interpolater. my %im; tie %im, 'InterpolateMethods'; # Example: Concatenation. print "The Foo object's attr attribute is: " . $foo->attr . "\n"; # Ugly inline print "The Foo object's attr attribute is: @{[$foo->attr]}\n"; # Use the interpolater print "The Foo object's attr attribute is: @im{ $foo->attr }\n"; # We can use the interpolater in list context as well. print "Calling Foo's Repeater(3) method yeilds: @im{ $foo->Repeater(3) + }\n"; package InterpolateMethods; use Tie::Hash; sub TIEHASH { my $self = shift; my $mi = \$self; return bless $mi, $self; } sub FETCH { my $self = shift; my $key = shift; return $key; } 1; __END__ The Foo object's attr attribute is: foo The Foo object's attr attribute is: foo The Foo object's attr attribute is: foo Calling Foo's Repeater(3) method yeilds: foo foo foo


TGI says moo

Replies are listed 'Best First'.
Re: Interpolating method calls
by Fletch (Bishop) on Sep 22, 2006 at 23:15 UTC

    Apologies to the Barenaked Ladies, but "It's All Been Done Before". Twice, in fact (although both by MJD and later passed on to be maintained by someone else).

      Sweet!

      And Interpolation is ever so much more evolved than my moment's dabbling. Thanks for the pointer.

      The ability to define special formatting functions looks very interesting.

      Any thoughts as to the wisdom of using said technique?


      TGI says moo

Re: Interpolating method calls
by bennymack (Pilgrim) on Sep 23, 2006 at 13:11 UTC