Friday, October 22, 2010

You're smarter than people say you are!

So my buddy "Horace" asked me how to do something in PERL.

OK, well, it's not like he asked how to do something in mi¢ro$oft Offic€. He was calling a database library that returned a hash reference, which he was using like this:

$foo = blahblah::hashref($what,$ever);
print OUTFILE "DATE:", $foo->{DATE}, "TYPE:", $foo->{TYPE} ...; 
The question was, rather than hard-coding the keys, wasn't there an easy way to find all the keys and dump the value corresponding to each key?

It seems like the sort of thing Larry would provide -- and because of the TMTOWTDI principle, probably provide more than one way to do it. I'm not a big fan of the TMTOWTDI principle because if you have to read other people's code, you eventually have to learn all the cockamamie ways people might have coded something.

It's this way in C, too; one can code ++a; or a++; or a+=1; or a=a+1; -- they all do the same thing. Similarly i[x] and x[i] mean the same thing: *(x+i). And strptr->fld is the same as (*strptr).fld

Back to Horace's problem. If we had an actual hash, rather than a hash reference -- e.g., if we had %bar rather than $foo -- then we'd simply code

foreach my $fld (keys %bar) { print "$fld $bar{$fld} "; }
Then I remembered an incantation I saw in a musty old volume...

I suggested trying it: using (keys %$foo) in the statement above. Horace typed it in and gave it a cockeyed look. "I'm not sure that'll even compile," he said. Just being supportive I guess. But much to his surprise...

$ perl -cw thescript.pl
thescript.pl syntax OK
$ 
Then he ran it; out came the keys and their values.

It was gratifying to see that my guess worked. Then came the best part. "You know, you're way smarter than people say you are."

It's nice to feel validated. I guess.

No comments: