Jon Bot Jon Bot - 2 months ago 13
Perl Question

Ternary operator doesn't allow iterative operator in it, but if-else does?

I noticed that if I replace the

if-else
statement I'm using with a ternary operator I end getting a compilation error when I try and run my code. I believe the culprit is the
foreach()
loop I have inside my
if-else
. Do you know why the ternary operator isn't behaving the same as the if-else construct in this instance?

My code looks like this

#!/program/perl_v5.6.1/bin/perl5.6.1

use strict;
use warnings;


my $fruits_array_ref = &get_fruits();
if($fruits_array_ref != 0) {
print("$_ is a fruit.\n") foreach(@$fruits_array_ref);
}
else {
print("Maybe you like vegetables?\n");
}


sub get_fruits() {
my @fruit_list;
my $shopping_list = "/home/lr625/grocery_items";

open(my $shopping_list_h, "<", $shopping_list) or die("Couldn't open.\n");
while(my $line = <$shopping_list_h>) {
next if $line =~ /^\#/;
chomp($line);
push(@fruit_list, $line);
}
close($shopping_list_h) or die("Couldn't close.\n");

scalar(@fruit_list) > 0 ? return(\@fruit_list) : return(0);
}


My data in the grocery list looks like

# this is a header
# to my grocery list
apple
banana
grape
orange


I'm replacing the
if-else
with a
?:
operator to look like this now in the main function.

my $fruits_array_ref = &get_fruits();
$fruits_array_ref != 0 ? print("$_ is a fruit.\n") foreach(@$fruits_array_ref) : print("Maybe you like vegetables?\n");


Also, for reference my error says.


syntax error at test.pl line 8, near ") foreach"

Execution of test.pl aborted due to compilation errors.

Answer

if-else is a flow control structure, ?-: is an operator that takes expressions as operands. foreach is a flow control structure, not an expression.

You can turn any block of code into an expression by using do:

$fruits_array_ref != 0
    ? do { print "$_ is a fruit.\n" for @$fruits_array_ref }
    : print "Maybe you like vegetables?\n";

But why?

Comments