foreach loops: fence post problem

I'd like to print out the strings in an array seperated by commas. The following code would work, except that the final comma is not followed by an element.

foreach my $e (@elements)
    print $e . ", ";

How can I write code that does not print the final comma? Thanks.
Who is Participating?
JustinPincarConnect With a Mentor Commented:
Theres a really easy way to do this.

Set the perl special list-seperator variable $, to something and then print the array.
For example...

@examples = ("hello", "goodbye", "cheesecake");

$, = ", ";

print @examples;

That will give you: hello, goodbye, cheesecake

kanduraConnect With a Mentor Commented:
Two suggestions:

1. check the entry for "join" in the perlfunc manpage.
2. check the meaning of $, in the perlvar manpage.
lth2hConnect With a Mentor Commented:
When I have to do something like this.  I first append the info to a variable, then use a regex to remove the extra comma, then print the variable.
Oh I forgot to add..

You can also include a counting variable and do it like this...

my $i=0;
foreach my $e (@array) {

if ($i == length(@array)) {
print $e;

} else {

print $e . ", ";



bobwood2000Author Commented:
Thanks! Using either $, or join is very elegant.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.