Jon Bot Jon Bot - 23 days ago 4
Perl Question

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

I noticed that if I replace the

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
loop I have inside my
. 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


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 =~ /^\#/;
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

I'm replacing the
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 line 8, near ") foreach"

Execution of aborted due to compilation errors.


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?