Cookie Notice

As far as I know, and as far as I remember, nothing in this page does anything with Cookies.

2010/08/23

Think Globally, Play With Hashes Locally

Reading a bit from Effective Perl Programming, I found out that Perl 5.12 supports deleting an element in a hash in a local scope. I was looking up from Higher Order Perl for a moment, so you might guess that my thoughts went to manipulating dispatch tables.



my %subs = ( do => sub { return 'c' },
rey => sub { return 'd' },
mi => sub { return 'e' },
fa => sub { return 'f' },
so => sub { return 'g' },
la => sub { return 'a' },
ti => sub { return 'b' }, ) ;

my @notes = qw( do rey mi fa so la ti do rum fmep agog ) ;

{
delete local $subs{ ti } ;
say '=' x 20 ;
for my $note ( @notes ) {
if ( $subs{ $note } ) {
my $sub = $subs{ $note } ;
say join "\t", '', $note, &$sub ;
}
}
}

say '-' x 20 ;
for my $note ( @notes ) {
if ( $subs{ $note } ) {
my $sub = $subs{ $note } ;
say join "\t", '', $note, &$sub ;
}
}

====================
do c
rey d
mi e
fa f
so g
la a
do c
--------------------
do c
rey d
mi e
fa f
so g
la a
do c

Yeah, I'm still on 5.10. But that made me think.
Can you add to a hash only in the local scope?

my %subs = ( do => sub { return 'c' },
rey => sub { return 'd' },
mi => sub { return 'e' },
fa => sub { return 'f' },
so => sub { return 'g' },
la => sub { return 'a' },
ti => sub { return 'b' }, ) ;

my @notes = qw( do rey mi fa so la ti do rum fmep agog ) ;

{
local $subs{ rum } = sub { return 'one' } ;
say '=' x 20 ;
for my $note ( @notes ) {
if ( $subs{ $note } ) {
my $sub = $subs{ $note } ;
say join "\t", '', $note, &$sub ;
}
}
}

say '-' x 20 ;
for my $note ( @notes ) {
if ( $subs{ $note } ) {
my $sub = $subs{ $note } ;
say join "\t", '', $note, &$sub ;
}
}

====================
do c
rey d
mi e
fa f
so g
la a
ti b
do c
rum one
--------------------
do c
rey d
mi e
fa f
so g
la a
ti b
do c


Yeah, I'm still on 5.10. But that made me think.
And you might guess that it's a foregone conclusion that you can modify a hash element locally.



my %subs = ( do => sub { return 'c' },
rey => sub { return 'd' },
mi => sub { return 'e' },
fa => sub { return 'f' },
so => sub { return 'g' },
la => sub { return 'a' },
ti => sub { return 'b' }, ) ;

my @notes = qw( do rey mi fa so la ti do rum fmep agog ) ;

{
#delete local $subs{ ti } ;
#local $subs{ rum } = sub { return 'one' } ;
local $subs{ ti } = sub { return 'FMEP' } ;
say '=' x 20 ;
for my $note ( @notes ) {
if ( $subs{ $note } ) {
my $sub = $subs{ $note } ;
say join "\t", '', $note, &$sub ;
}
}
}

say '-' x 20 ;
for my $note ( @notes ) {
if ( $subs{ $note } ) {
my $sub = $subs{ $note } ;
say join "\t", '', $note, &$sub ;
}
}

====================
do c
rey d
mi e
fa f
so g
la a
ti FMEP
do c
--------------------
do c
rey d
mi e
fa f
so g
la a
ti b
do c

The more I play with dispatch tables, the more I imagine practical uses of this. I love cool stuff!