I have a Perl CGI script. I'm trying to generate hyperlinks on an HTML page using all the elements in an array. I'm using functional CGI style programming. Here's a minimal representation of my code:
#!/usr/bin/perl
use strict; use warnings;
use CGI qw( :standard);
print header;
print start_html(
-title => 'Get LINK!'
);
my %HoA = (
'foo' => [ '12', '23', '593' ],
'bam' => [ '232', '65' ],
);
my @array = ("foo", "bam");
foreach my $i (@array){
foreach my $j (@{$HoA{$i}}){
my $link = get_link($i);
print "<a href="$link" target="_blank">$i</a>"."\t"; # this doesn't work!!
}
}
#-----------------------------------
# this subroutine works!
sub get_link{
my $id = $_[0];
my $link = 'http://www.example.com/'.$id;
return $link;
}
#------------------------------------
Any help or suggestions are appreciated.
print "<a href="$link" target="_blank">$g</a>"."\t"; # this doesn't work!!
that's because your quotes in your quote end your quote. You need to escape them:
print "<a href=\"$link\" target=\"_blank\">$g</a>"."\t"; # this doesn't work!!
single quotes work on the inside, too.
As per the comment, qq-style quoting is also available to you, so you can use double quotes and variable interpolation at the same time without the escape characters.
There's a few things that don't make much sense.
The code below doesn't work because $link
is a ref. Also, you're not using $j
anywhere, which should give you a sign that there's a bit of a "design" issue.
foreach my $i (@array){
foreach my $j (@{$HoA{$i}}){
my $link = get_link($i);
print "<a href="$link" target="_blank">$g</a>"."\t"; # this doesn't work!!
}
}
Why can't this be rewritten like so:
for my $array_ref (keys %HoA) {
for my $item ( @{ $HoA{$array_ref} } ){
my $link = get_link($item);
# print ....
}
}
How does this sub "work"? $id
is an array reference here. Do you just mean to shift
onto $id?
#-----------------------------------
# this subroutine works!
sub get_link{
#my $id = $HoA{$_[0]};
# with the refactored double for loop, or the way you had it if you fix the
# `ref` issue, a `shift` should do the trick.
my $id = shift;
my $link = 'http://www.google.com/'.$id;
return $link;
}
#------------------------------------
You also need to escape the quotes in print
statement:
print "<a href="$link" target="_blank">$g</a>"."\t";
Here is another way you can do this ...
use strict;
use warnings;
use CGI qw(:standard);
print header,
start_html(-title => 'Get LINK!');
my %HoA = (
foo => [ qw(12 23 593) ],
bam => [ qw(232 65) ],
);
foreach my $i ( reverse sort keys %HoA ) {
foreach ( @{$HoA{$i}} ) {
print a({-href => 'http:/www.google.com/'.$_,
-target => '_blank'}, $i) . "\n";
}
}
Output:
foo foo foo bam bam
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.