On Fri, Apr 19, 2002 at 01:35:10PM -0000, Lars Henrik Mathiesen wrote: > > Date: Thu, 18 Apr 2002 23:44:26 +0200 > > From: Paul Johnson <[EMAIL PROTECTED]> > > > > On Thu, Apr 18, 2002 at 07:56:06PM -0000, Lars Henrik Mathiesen wrote: > > > I would like to write > > > > > > for my $key ( $hash{foo}->keys ) { print $hash{bar}->{$key} } > > > > This, or something similar was hashed out on p5p, ooooh, about 4 years > > ago, give or take four years ;-) Actually, I think it might have been > > when Chip was Pumpking, which would have made it about five years ago. > > I'm not surprised that other people suggested it... and I'm sure that > there are good arguments against as well. > > Hmmm... I just realized that it's possible to get almost the same > thing by misusing bless: > > package hash; > sub bless { bless shift } > sub keys { keys %{+shift} } > sub values { values %{+shift} } > sub hash { %{+shift} } > > package main; > > my $href = hash::bless { foo => 1, bar => 2 }; > > print join ', ', $href->keys; > print join ', ', $href->values; > print join ', ', $href->hash; > > Tempting --- now if only I could create a method named % or @ ... I'm > not sure how many optimizations this loses relative to the %{ $href } > construction, though.
Creating methods with names '%', '@' or whatever isn't the problem. The problem is calling them. #!/usr/bin/perl -w use strict; package hash; sub bless { bless shift } { no strict 'refs'; *{'hash::@'} = sub {keys %{+shift}}; *{'hash::*'} = sub {values %{+shift}}; *{'hash::%'} = sub {%{+shift}} } package main; my $href = hash::bless { foo => 1, bar => 2 }; $\ = "\n"; $, = ", "; print $href -> $_ foreach qw /@ * %/; __END__ Running this gives: foo, bar 1, 2 foo, 1, bar, 2 But '$href -> %' and also '$href -> "%"' are syntax errors. You can put a variable on the right side of an arrow, but not a literal string. Abigail