in reply to Tied Variables - why?

To add to these other good examples, take CGI.pm

Often I'll have to generate a select tag (popup_menu) with different key and values. The way to do this in CGI.pm is by passing a hash. Usually you'll want them sorted by the display value, but hashes are intrinsically unordered.

What to do?

Simple
# Kludge to get options sorted. package MySortHash; use Tie::Hash; use vars qw(@ISA); @ISA = qw( Tie::StdHash ); sub FIRSTKEY { my $self = shift; @{ $self->{VERY_UNLIKELY_HASH_KEY} } = sort {$self->{$a} cmp $self +->{$b} } grep { $_ ne 'VERY_UNLIKELY_HASH_KEY' } keys %{$self}; return shift @{ $self->{VERY_UNLIKELY_HASH_KEY} }; } sub NEXTKEY { my $self = shift; return shift @{ $self->{VERY_UNLIKELY_HASH_K +EY} }; } # later in package main... tie %thash, 'MySortHash' ; # tied hash with sorted keys... print $q->popup_menu(-name=>$p , labels=> \%thash, -values=> [ (keys % +thash) ] );
Now I could subcass CGI and muck around with popup_menu or I could write yet another CGI module but why when I can coax CGI.pm into DWIM with in 10 lines of code? My favorite uses usually are coaxing some new behavior out of existing code. Paging/Filtering filehandles.. etc.

-Lee

"To be civilized is to deny one's nature."

Replies are listed 'Best First'.
Re^2: Tied Variables - why?
by Aristotle (Chancellor) on Sep 07, 2002 at 11:15 UTC
    Good example, but you could cut down further. :-)
    use Tie::IxHash; tie %thash, Tie::IxHash; print $q->popup_menu(-name => $p, labels => \%thash, -values => [ keys + %thash ]);

    Makeshifts last the longest.

      Good point. In CGI scripts, I like to keep the number of modules that need to be loaded down when it makes sense. Especially small things like this but YMMV.

      -Lee

      "To be civilized is to deny one's nature."

        I used to be in that camp too. Nowadays I don't confine myself though unless there is no pure-Perl module for the purpose. The reason is simple: any Perl code can be placed where a CGI script can, so any pure-Perl modules can be passed along with the script - even if I have to download the modules and copypaste the code into the file myself.

        Care needs to be taken that all the imports work correctly of course, but it's far from impossible. I'm thinking some sort of packaging mechanism based on Coderefs in @INC (was: Building a Simple Perl Module Database) could actually make the whole thing totally transparent.

        Makeshifts last the longest.