Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print 'AND' between array elements?

Tags:

arrays

perl

If I have an array with name like below.

How do I print "Hi joe and jack and john"?

The algorithm should also work, when there is only one name in the array.

#!/usr/bin/perl

use warnings;
use strict;

my @a = qw /joe jack john/;

my $mesg = "Hi ";

foreach my $name (@a) {

    if ($#a == 0) {
    $mesg .= $name;
    } else {
    $mesg .= " and " . $name;
    }
}

print $mesg;
like image 539
Sandra Schlichting Avatar asked Dec 10 '22 06:12

Sandra Schlichting


1 Answers

Usually we use an array join method to accomplish this. Here pseudo code:

@array = qw[name1 name2 name2];
print "Hey ", join(" and ", @array), ".";
like image 52
Kaken Bok Avatar answered Jan 29 '23 18:01

Kaken Bok