469,310 Members | 2,439 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,310 developers. It's quick & easy.

How to tell the last iteration in a foreach loop?

Expand|Select|Wrap|Line Numbers
  1. foreach $key (keys (%hash)){
  2.   print "$hash{$key}:";
  3. }
  4.  
The last element will also be followed by a ":" which is not what I want. Is there a way to tell when foreach loops to its last round, so that I can skip printing the last ":"? Thanks!
Sep 26 '08 #1
5 8502
numberwhun
3,503 Expert Mod 2GB
First, please use code tags, they are required.

Second, can you provide a sample of the data so we can see what you are talking about?

Regards,

Jeff
Sep 26 '08 #2
KevinADC
4,059 Expert 2GB
already answered on tek-tips

Expand|Select|Wrap|Line Numbers
  1. print join(':', map{$hash{$_}} keys %hash); 
Sep 27 '08 #3
for example assume i have an array i.e,
Expand|Select|Wrap|Line Numbers
  1. my @a = (1,2,3,4,5,6);
  2.  
  3. for(my $i = 0;$i<$#a;$i++) {
  4.          print $a[$i];
  5. }
  6.  
Above for loop we r excluding last element to print;
Sep 29 '08 #4
Ganon11
3,652 Expert 2GB
That's because you have i<$#a - use i<=$#a instead.

Better yet, use a foreach loop:

Expand|Select|Wrap|Line Numbers
  1. for my $element (@a) {
  2.    print $element;
  3. }
Sep 29 '08 #5
KevinADC
4,059 Expert 2GB
for example assume i have an array i.e,
Expand|Select|Wrap|Line Numbers
  1. my @a = (1,2,3,4,5,6);
  2.  
  3. for(my $i = 0;$i<$#a;$i++) {
  4.          print $a[$i];
  5. }
  6.  
Above for loop we r excluding last element to print;

Next time post a new thread.
Sep 29 '08 #6

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

6 posts views Thread by Mike P | last post: by
7 posts views Thread by Robert Bravery | last post: by
23 posts views Thread by Florian Lindner | last post: by
10 posts views Thread by fig000 | last post: by
1 post views Thread by Perl Beginner | last post: by
23 posts views Thread by tshad | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by harlem98 | last post: by
1 post views Thread by Geralt96 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.