By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,691 Members | 2,041 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,691 IT Pros & Developers. It's quick & easy.

How to tell the last iteration in a foreach loop?

P: 1
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
Share this Question
Share on Google+
5 Replies


numberwhun
Expert Mod 2.5K+
P: 3,503
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
Expert 2.5K+
P: 4,059
already answered on tek-tips

Expand|Select|Wrap|Line Numbers
  1. print join(':', map{$hash{$_}} keys %hash); 
Sep 27 '08 #3

P: 4
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
Expert 2.5K+
P: 3,652
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
Expert 2.5K+
P: 4,059
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.