Re: [htmltmpl] (newbie) How to populate an array of hash references one by one?
Brought to you by:
samtregar
From: Timm M. <tm...@ag...> - 2003-11-24 20:03:37
|
><> ># attempt 1 >my @test = (); >push @test { name=>"foo",value=>"blitz" }; ># Gets "Global symbol "%test" requires explicit package name at ...[push >line]" !?!?! there is no %test. You forgot a comma, so Perl interpreted it as something like this: push @test{'name','foo',value','blitz'}; Adding a comma after @test will make it work ># attempt 2 >my @test = (); >push @test \{ name=>"foo",value=>"blitz" }; ># Gets "Backslash found where operator expected at ...[push line]" This would have made a reference to a hash reference (if you had the comma in), which wouldn't have worked anyway. ><> ># attempt 4 >my @test = [ > { a=>"b",c=>"d" }, > { e=>"f",g=>"h" }, >]; >$template->param(itemloop => \@test); ># Gets "HTML::Template->output() : fatal error in loop output : >HTML::Template->param() : Single reference arg to param() must be a >has-ref! You gave me a ARRAY. at ..." To Perl, you're creating an array, the first element being an arrayref, which contains hashrefs. What you actually wanted to do is: my @test = ( { a=>"b",c=>"d" }, { e=>"f",g=>"h" }, ); Note parens instead of square brackets. ># attempt 5 >my %test; >$test{"a"}="b"; >$test{"c"}="d"; >$test{"e"}="f"; >$template->param(itemloop => \%test); ># Gets "HTML::Template::param() : attempt to set parameter 'itemloop' >with a scalar - parameter is not a TMPL_VAR! at ..." This one is interesting. Looks like HTML::Template trys to use the hashref in its scalar representation (like HASH(0xffffffff)) and then errors out when your param isn't a loop. ># attempt 6 >my %test; >$test{"a"}="b"; >$test{"c"}="d"; >$test{"e"}="f"; >$template->param(itemloop => %test); ># Gets "You gave me an odd number of parameters to param()! at ..." To Perl, your params are being flatened like this: $template->param(itemloop => a, b => 'c', d => 'e', f ); That's because the param method takes a list with all the parameters being flattened into a hash. Since you're putting 'itemloop => ' first, Perl sees that as the first element in the hash. That's why you need to use references. Please read perldsc. <> |