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

Ok, so I'm trying to use Text::Sprintf::Named -- I'm looking for the functionality to do something similar to GNU /bin/find's -printf. The catch is I'm using Moose lazy/default, so I don't want the unneeded accessors to be used at all. I'm wondering if there is a pragma or module that changes the way perl works to allow this behavior:

sub value { die 'bad' } my $hash = { "key" => value() } die 'good'

I want that example to die with good. So I'm looking to make a whole hash lazy. I'm kind of just thinking out loud and playing around. I can't return a subref because T::S::N doesn't accept it. Ideally, T::S::N, would also support values deeper in a hash, { key => { title => 'foo', value => 'bar' } } or execute by $obj->$name. ;) If anyone else has done an exercise like this please give your input. I'm writing a printf filter for postgres's EXPLAIN



Evan Carroll
www.EvanCarroll.com

Replies are listed 'Best First'.
Re: Printf in perl / Lazy hash possible?
by moritz (Cardinal) on Aug 27, 2007 at 07:16 UTC
Re: Printf in perl / Lazy hash possible?
by diotalevi (Canon) on Aug 29, 2007 at 15:40 UTC

    This is trivial. Store a delayed computation.

    %hash = ( key => sub { value() } );

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

      This is actually the conclusion that I arrived at too, but it seems ugly. I'll post again, and present this as a "How would you write the following code".


      Evan Carroll
      www.EvanCarroll.com

        It's only ugly because you're using perl. If you were in another language where you were used to seeing "lambda" all the time in user code it'd be ordinary. If you were using Haskell you wouldn't even have to be explicit about it. Since you're using Perl, you've got to live with what you've got. Or enact dizzying schemes of fantastic magicalism. I hope all that machinery is worth it just to get rid of the sub { ... }.

        ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊