fivefiftyone has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,

I'm currently attempting to piece together a program that will generate a URL I need, drawing on a list of serial numbers from a DB. Thing is, the list of serial numbers needs to be comma separated, which would be easy enough with join(",", @array). Alas, no matter where I attempt said join, Perl laughs at me and produces the list of undelimited serial numbers.

The code I have so far:
my $ref = $sth->fetchall_arrayref(); foreach my $result (@$ref) { $sn .= $result->[0]; } return $sn; $sth->finish(); $dbh->disconnect();
The desired result, when paired with the first part of the URL, would be XXXX-XXXX,XXXX-XXXX, not the XXXX-XXXXXXXX-XXXX I am left with.

I've tried this on a while() loop using $sth->fetch_array(), pre-declaring the array and trying to join it. I knew it was empty and I knew it wouldn't work, but then I've never mastered the art of thinking things through. I've also tried applying the join() inside of the loop, or applying to the LHS and RHS of my $sn .= $result[0] / $result->[0], neither of which worked either.

Anyway, the program in its incomplete entirety:
#!/us/bin/perl + + + use strict; use warnings; use DBI; use LWP::UserAgent; sub get_serialno { my $dbh = DBI->connect("DBI:mysql:database=stuff;host=localhost", "w +oo", "hoo", {'RaiseError' => 1}) || die "Error: " . DBI->errstr; my $sth = $dbh->prepare("SELECT serialno FROM appliances"); $sth->execute(); my $sn; my $ref = $sth->fetchall_arrayref(); foreach my $result (@$ref) { $sn .= $result->[0]; } return $sn; $sth->finish(); $dbh->disconnect(); } my $asyncos = shift || die "Usage: imagefetch.pl <version number>-<bui +ld>\n"; my ($version, $build) = split /-/, $asyncos; (my $mversion = $version) =~ s/\./-/g; my $urlpart = "http://downloads.ironport.com/asyncos/upgrade/asyncos-$ +mversion.ipup?requested_version=phoebe-$mversion-$build&serial="; my $snpart = get_serialno; my $url = $urlpart . $snpart; print $url; print "\n\n";
The LWP stuff itself will be simple. Running out of talent (or tutorials!) at a small hurdle like this is um, annoying :). A clue, a smack upside the head or a RTFM (please include a hyperlink) all welcome.

Many thanks in advance.
UPDATE: Fixed with one line of code. Must try harder next time.

Replies are listed 'Best First'.
Re: Using join() on a MySQL arrayref
by jhourcle (Prior) on Jun 19, 2008 at 18:51 UTC
        $sn .= $result->[0];

    You're not adding any delimiter between the values ... just concatenating them. Try replacing the while loop with:

    $sn = join(',', map { $_->[0] } @$ref);
      Thank you. I'll be kicking myself for not delving a little deeper.