Wick
Wick

Reputation: 1232

using a counter variable in Perl hash key names

I've got a bunch of HTML form field data coming in as a hash, where each field name becomes the key & the field value is the hash value... your standard CGI module output from:

my $query = new CGI;
my %formdata = $query->Vars;

This time I'm working with a collection of multiple form fields that each have a numeric suffix ("name1" "name2" ... "size1" "size2" etc). Is there a better way to use a counter to loop through the group of those in numeric order than this?

for (my $i = 1; $i < 10; $i++) {
  print "  Name $i: " . $formdata{"name$i"} . "\n";
  print "  Size $i: " . $formdata{"size$i"} . "\n";
}

...This isn't bad but is there a simpler syntax? I.e. like this (but this doesn't work - Can't call method "name" without a package or object reference):

  print "  Name $i: $formdata{name$i}\n";

Upvotes: 1

Views: 1875

Answers (3)

ikegami
ikegami

Reputation: 386331

If you want to use " in a string delimited by ", escape it.

print "  Name $i: $formdata{\"name$i\"}\n";

Or change the delimiter.

print qq{  Name $i: $formdata{"name$i"}\n};

Or avoid using ".

print "  Name $i: $formdata{qq{name$i}}\n";
print "  Name $i: $formdata{'name'.$i}\n";
printf "  Name %s: %s\n", $i, $formdata{"name$i"};
print "  Name $i: " . $formdata{"name$i"} . "\n";

Upvotes: 1

friedo
friedo

Reputation: 67028

I usually do this sort of thing by making a list of keys based on the form name prefix. For example,

my @numbers = sort map { /name(\d+)/ } keys %formdata;
foreach my $num( @numbers ) { 
    print "  Name $num: ", $formdata{ 'name' . $num }, "\n";
    ...
}

This has the advantage of working for any number of form elements.

Upvotes: 2

ruakh
ruakh

Reputation: 183456

The obvious solution doesn't work:

  print "  Name $i: $formdata{"name$i"}\n";

but can be fixed by replacing either of the sets of actual double-quotes "..." with the qq operator (qq{...} or qq(...) or qq/.../ or whatever-you-like):

  print qq{  Name $i: $formdata{"name$i"}\n};

See "Quote and Quote-like Operators" in the perlop man-page.

Upvotes: 6

Related Questions