开发者

How to print 'AND' between array elements?

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;


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

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


Untested:

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


Just use the special variable $".

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


To collect the perldoc perlvar answers, you may do one of (at least) two things.

1) Set $" (list separator):

When an array or an array slice is interpolated into a double-quoted string or a similar context such as /.../ , its elements are separated by this value. Default is a space. For example, this:

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

is equivalent to this:

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

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

2) Set $, (output field separator):

The output field separator for the print operator. If defined, this value is printed between each of print's arguments. Default is undef. Mnemonic: what is printed when there is a "," in your print statement.

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

Either will work, and either may be used with local to set the value of the special variable only within an enclosing scope. I guess the difference is that with $" you are not limited to the print command:

my @z = qw/ a b c /;
local $" = " and ";
my $line = "@z";
print $line;

here the "magic" happens on the 3rd line not at the print command.

In truth though, using join is the most readable, and unless you use a small enclosing block, a future reader might not notice the setting of a magic variable (say nearer the top) and never see that the behavior is not what is expected vs normal performance. I would save these tricks for small one-offs and one-liners and use the readable join for production code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜