On Mon, Apr 20, 2009 at 12:26, Dermot <paik...@googlemail.com> wrote: > 2009/4/20 Chas. Owens <chas.ow...@gmail.com>: >> On Mon, Apr 20, 2009 at 11:21, Dermot <paik...@googlemail.com> wrote: > ... >>> I thought that I could say somethign >>> like, "if %defaults, return %defaults else populate %defaults and >>> return". >>> >>> Here's the error I am getting: >>> >>> Can't modify private hash in logical or assignment (||=) at >>> /export/web/lib/Foo.pm line 28, near "} >> snip >> >> You should have gone with your first instinct: >> >> sub getDefaults { >> >> return if %defaults; >> >> >> my $sql = q{SELECT * from bar}; >> my $sth = $dbh->prepare($sql); >> $sth->execute; >> while (my $row = fetchrow_hashref) { >> $defaults{$row->{id}} = $row->{'description'}; >> } >> return >> } > > Just so I'm clear because it's actually quite a hard thing to test, my > sub should look start like this: > > my %defaults # Declared globally; > > sub getDefaults { > return if %defaults; > %defaults = do {...} > } snip
I would avoid the do {...} and just muck with %defaults directly (as I did in the example). snip >> You might also want to look into the Singleton pattern[1]. >> >> 1. http://en.wikipedia.org/wiki/Singleton_pattern > > > Design patterns. I have come across this term a few times but there is > very little Perl examples of Design Patterns around and not a single > example of Singleton pattern on that page :-( snip Here you go: http://perldesignpatterns.com/?PerlDesignPatterns http://perldesignpatterns.com/?SingletonPattern -- Chas. Owens wonkden.net The most important skill a programmer can have is the ability to read. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/