Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl ternary conditional operator

I'm trying to write more efficient code in my scripts and have been implementing ternary conditional operators on occasion. I can't understand why I am getting an additional result when using a ternary conditional operator in a loop:

#!/usr/bin/perl

use strict;
use warnings;

my @array = ('Serial = "123"', 'Serial = "456"', 'Serial = "789"');
my ($test1,$test2);
foreach my $a (@array){
        !$test1 ? $test1 = $a  : $test1 .= " AND " . $a;
}
foreach my $b (@array){
        if (!$test2) {
                $test2 = $b
        } else {
                $test2 .= " AND " . $b;
        }
}
print "Test1: $test1\n";
print "Test2: $test2\n";

Output:

~/bin/test.pl
Test1: Serial = "123" AND Serial = "123" AND Serial = "456" AND Serial = "789"
Test2: Serial = "123" AND Serial = "456" AND Serial = "789"

Test1 output has an additional "Serial = "123", What am I doing wrong?

like image 532
Mose Avatar asked Nov 29 '22 03:11

Mose


1 Answers

First, you have a precedence problem.

!$test1 ? $test1 = $a : $test1 .= " AND " . $a;

means

( !$test1 ? $test1 = $a : $test1 ) .= " AND " . $a;

It can be solved with parens.

my $test1;
for (@array) {
   !$test1 ? ($test1 = $a) : ($test1 .= " AND " . $a);
}

But that's not readable. You're obviously going in the wrong direction! There are two tasks being performed, and you are trying to jam them into one. Simply separating them makes the code much more readable.

my $test1;
for (@array) {
   $test1 .= ' AND ' if $test1;
   $test1 .= $_;
}

But we're not there yet. Let me introduce you to join.

my $test1 = join(' AND ', @array);

So much better!

Finally, it sure looks like you are building an SQL statement. If so, your question is moot since you should USE PLACEHOLDERS TO TRANSFER DATA TO A DATABASE. Search the DBI documentation for that word.

like image 199
ikegami Avatar answered Dec 15 '22 04:12

ikegami