Re: Accessing variable hash elements

"Simon McCaughey" <[email protected]>
Newsgroups gmane.comp.lang.perl.modules.petal
Message-ID <00fa01c54cec$e2ba4c20$b7f8a52f@AtticPC>
So, I ended up writing a little modifier, because the case changed slightly. 

I want to use $variable to access a hash element such as:
$hash->{$variable}
*** and ***
$hash->{$variable}->{'value'}

So I wrote the following Modifier called lookup:  
$Petal::Hash::MODIFIERS->{'lookup:'} = sub {
    my $hash = shift;   
    my $args = shift;     
    my @args = split(/\s+/, $args);
    ##the first is the hash name
    my $the_hash = $hash->fetch ($args[0]);
    my $param    = $hash->fetch ($args[1]);
    if($args[2])        
    {                       
        return $the_hash->{$param}->{$args[2]};
    }
    else
    {
        return $the_hash->{$param};
    }
};
This is used in the code like:

<span tal:replace="lookup: the_hash variable field_name">replace me</span>

and it works nicely

I know I have no real validation built in yet, but that aside, any comments?

Regards

Simon


  ----- Original Message ----- 
  From: [email protected] 
  To: Petal Mailing List 
  Sent: Friday, April 29, 2005 1:38 PM
  Subject: [Petal] Accessing variable hash elements


  Ok, I know this must be a stupid question, I probably just need more caffeine but.....

  I need to access a variable hash element $user{$group}

  if I have a Hash as : 
  my %user = ( name => 'Simon', group1 => '1', group3 => '1') ;

  and an array like :
  my @groups = (qw/group1 group2 group3/ );

  and I want to do:

  <td tal:repeat="group groups">
      <span tal:content="user group">is the user in the group</span>
  </td>

  I know this last bit is incorrect, but there must be a simple way of accessing $user{$group}

  Thanks

  Simon
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.