in reply to Why does this code break if I properly set the scope?
which won't work right if any vendor name is a substring of another. Another potential problem arises if the URL is not defined. Perhaps there are other problems with the input data.if ( $config[$m]{Vendor} =~ /$products[$n]{Name}/ ) {
Here's a version of your code with some example data and some debugging, which works for me:
#!/usr/bin/perl use strict; use warnings; use diagnostics; my @products = ( { 'Prod' => 'pencil', 'Name' => "Staples", 'Vendor Item ID' => " +1", }, { 'Prod' => 'paper', 'Name' => "OfficeMax", 'Vendor Item ID' => " +2", }, { 'Prod' => 'eraser', 'Name' => "Walgreens", 'Vendor Item ID' => " +3", }, ); my @config = ( { 'Vendor' => "Staples", 'URL' => "http://staples/item=*", }, { 'Vendor' => "OfficeMax", 'URL' => "http://officemax/item=*", }, { 'Vendor' => "Walgreens", 'URL' => "http://walgreens/item=*", }, ); my ($n, $m, $url); print_products("BEFORE"); $n=0; for my $el (@products) { if ( exists $products[$n]{"Vendor Item ID"} ) { $m = 0; for my $el (@config) { if ( exists $config[$m]{Vendor} ) { if ( $config[$m]{Vendor} =~ /$products[$n]{Name}/ ) { $url= $config[$m]{URL}; $url=~ s/\*/$products[$n]{"Vendor Item ID"}/g; $products[$n]{TaggedID} = $url; } } $m++; } } $n++; } print_products("AFTER"); sub print_products { my ($msg) = @_; print "$msg\n" if defined $msg; my $count = 0; foreach my $prod (@products) { $count++; print "$count:"; foreach my $key (sort keys %$prod) { print " \"$key\"=\"".$$prod{$key}."\""; } print "\n"; } }
And, since you asked for better ways to do it, here is the main loop the way I would have written it:
foreach my $prod (@products) { next if !exists $$prod{'Vendor Item ID'}; my $viid = $$prod{'Vendor Item ID'}; my $name = $$prod{'Name'}; foreach my $conf (@config) { next if !exists $$conf{'Vendor'}; if ( $$conf{'Vendor'} eq $name ) { next if !exists $$conf{'URL'}; my $url = $$conf{'URL'}; $url =~ s/\*/$viid/; $$prod{'TaggedID'} = $url; last; } } }
|
|---|