A
A. Farber
Hi, I have a simple problem, which I have solved, but
my solution feels ugly to me. Any improvements please?
A web form contains a list of project names. And for
some projects there are mailing lists, which I need
to display if the matching project has been selected.
Some project names begin with the same string, like
"p1881_aq_" and "p1881". In those cases only the longest
match should be taken. Here is how I tried to solve it:
# put the longest keys first, to make them win
my @KEYS = qw( p1881_aq_ p1881_ p1972_ p1981_ p2311_ );
my %MAIL = (p1881_aq_ => {name => 'Project Aqua',
mail => '(e-mail address removed)'},
p1881_ => {name => 'Project Alpha',
mail => '(e-mail address removed)'},
p1972_ => {name => 'Project Beta',
mail => '(e-mail address removed)'},
p1981_ => {name => 'Project Gamma',
mail => '(e-mail address removed)'},
p2311_ => {name => 'Project Theta',
mail => '(e-mail address removed)'},
);
......
for my $p (@selected_projects) {
for my $k (@KEYS) {
if (0 == index $p, $k) {
printf q{<A HREF="MAILTO:%s">%s</A>},
$MAIL{$k}->{mail}, $MAIL{$k}->{name};
last;
}
}
}
my solution feels ugly to me. Any improvements please?
A web form contains a list of project names. And for
some projects there are mailing lists, which I need
to display if the matching project has been selected.
Some project names begin with the same string, like
"p1881_aq_" and "p1881". In those cases only the longest
match should be taken. Here is how I tried to solve it:
# put the longest keys first, to make them win
my @KEYS = qw( p1881_aq_ p1881_ p1972_ p1981_ p2311_ );
my %MAIL = (p1881_aq_ => {name => 'Project Aqua',
mail => '(e-mail address removed)'},
p1881_ => {name => 'Project Alpha',
mail => '(e-mail address removed)'},
p1972_ => {name => 'Project Beta',
mail => '(e-mail address removed)'},
p1981_ => {name => 'Project Gamma',
mail => '(e-mail address removed)'},
p2311_ => {name => 'Project Theta',
mail => '(e-mail address removed)'},
);
......
for my $p (@selected_projects) {
for my $k (@KEYS) {
if (0 == index $p, $k) {
printf q{<A HREF="MAILTO:%s">%s</A>},
$MAIL{$k}->{mail}, $MAIL{$k}->{name};
last;
}
}
}