I am quite new to Perl, and have not had much luck finding a cause for some seemingly-strange behavior of a Perl script I am playing around with. I am running Perl 5.8.6 on OS X 10.4.8. I have done some perusing, but I'm not quite sure how to describe what I'm seeing so I haven't had much luck.

$text = "JEZEBEL (Disc, 1938)";
my @temp = split (/\(/, $text);
$title = substr(@temp[0], 0, - 1);
my @temp2 = split (/,/, @temp[1]);
$format = substr(@temp2[0], 0);
$r_date = substr(@temp2[1], 1, - 1);

my $sql = "INSERT INTO movies (TITLE, MEDIA, YEAR) VALUES ('".$title1."', '".$format1."', ".$r_date1.")";
print $sql;

This code gives the following output.

INSERT INTO movies (TITLE, MEDIA, YEAR) VALUES ('JEZEBEL', '', )INSERT INTO movies (TITLE, MEDIA, YEAR) VALUES ('', 'Disc', 1938)

I cannot understand why the output becomes seperated like this, with one variable inserted properly into the first statement and the other two into the second - and its not something that is happening to the output in my terminal, as I can see the same problem in my database when I run it as an SQL statement. When I look at each variable individually it seems to be correct, but when I try to concatenate them I always seem to end up with two statements like this. Any thoughts on why this is occuring? Could it be that the second two variables are some type of array? Thanks a lot for the help.

Recommended Answers

All 4 Replies

I think what might be wrong here is that Perl treats both single and double quotes as string terminators, whether you started the string with a single or double quote. My advice is try escaping the single quotes in your string with back slashes ( \ ). So the line in question should be:

my $sql = "INSERT INTO movies (TITLE, MEDIA, YEAR) VALUES (\'" . $title1 . "\', \'" . $format1 . "\', ".$r_date1."\')";

I might be wrong but it's worth a try :) .

Steven.

jemather,

the code you posted shouldn't even produce values for the scalars in the $sql scalar.

('".$title1."', '".$format1."', ".$r_date1.")"

there are no $title1 or $format1 or $date1 scalars defined in the code you posted. You have $title and $format and $r_date.

with the correct scalars, the line is better written without using any concatenation at all:

my $sql = "INSERT INTO movies (TITLE, MEDIA, YEAR) VALUES ('$title', '$format', $r_date)";

Steven,

single-quotes inside of double-quoted strings have no special meaning. No need to escape them.

if $text is always in that same format:

$text = "JEZEBEL (Disc, 1938)";
my ($title,$format,$r_date) = $text =~ /^(\S+)\s*\(([^,]+),\s*(\d+)\)/;
my $sql = "INSERT INTO movies (TITLE, MEDIA, YEAR) VALUES ('$title', '$format', $r_date)";
print $sql;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.