How to print 'AND' between array elements?

If I have an array named as shown below.

How to print "Hello, 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; 
+4
source share
4 answers

Usually we use an array join method to achieve this. Here's the pseudo code:

 @array = qw[name1 name2 name2]; print "Hey ", join(" and ", @array), "."; 
+8
source

Unverified:

 { local $, = " and "; print "Hi "; print @a; } 
+2
source

Just use the special variable $" .

 $"="and"; #" (this last double quote is to help the syntax coloring) $mesg="Hi @a"; 
+2
source

To compile perldoc perlvar answers, you can do one of (at least) two things.

1) Set $" (list separator):

When an array or slice of an array is interpolated into double quotation marks, a string or similar context, such as /.../, its elements are separated by this value. The default value is a space. For example, this:

 print "The array is: @array\n"; 

equivalent to this:

 print "The array is: " . join($", @array) . "\n"; 

=> $" affects the behavior of interpolating an array into a string

2) Set $, (output field separator):

Output field separator for the print statement. If specified, this value is printed between each print argument. The default is undef. Mnemonics: what is printed when there is a "," in your print statement.

=> $, affects the behavior of the print statement.

It will either work, or it can be used with local to set the value of a special variable only within the scope. I think the difference is that with $" you are not limited to the print command:

 my @z = qw/ abc /; local $" = " and "; my $line = "@z"; print $line; 

here the "magic" happens on the third line, and not on the print command. A.

In truth, using join is the most readable one, and if you don’t use a small closed block, the future reader may not notice the settings of the magic variable (say, closer to the top) and never see that the behavior is not what is expected against normal performance. I would save these tricks for small one-time and one-line and use readable join for production code.

+2
source

All Articles