• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 561
  • Last Modified:

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.
0
bobwood2000
Asked:
bobwood2000
3 Solutions
 
kanduraCommented:
Two suggestions:

1. check the entry for "join" in the perlfunc manpage.
2. check the meaning of $, in the perlvar manpage.
0
 
lth2hCommented:
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.
0
 
lth2hCommented:
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 . ", ";

}

$i++;

}
0
 
JustinPincarCommented:
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

~Justin
0
 
bobwood2000Author Commented:
Thanks! Using either $, or join is very elegant.
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now