substr problem

Please support our Perl advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: Nov 2008
Posts: 70
Reputation: orwell84 is an unknown quantity at this point 
Solved Threads: 3
orwell84's Avatar
orwell84 orwell84 is offline Offline
Junior Poster in Training

substr problem

 
0
  #1
Apr 18th, 2009
I'm having a problem with the substr function. I want it to be dynamic in a for loop as follows:
  1. for ($i = substr $bin, $sub, 1 ; $sub < $len2 ; $sub++){
You can probably guess what this code is meant to do. I want to read each character in the string separately and operate on it in the for loop. The problem is that this code doesn't do what I want it to do. Is there a way to use substr for this? Is there a better way to do what I'm trying to do, possibly without substr? Thanks in advance for any help.
Reply With Quote Quick reply to this message  
Join Date: Mar 2006
Posts: 898
Reputation: KevinADC has a spectacular aura about KevinADC has a spectacular aura about 
Solved Threads: 67
KevinADC's Avatar
KevinADC KevinADC is offline Offline
Practically a Posting Shark

Re: substr problem

 
0
  #2
Apr 18th, 2009
use split instead:

  1. my $var = 'abcdefghijklmnop';
  2. my @chars = split(//,$var);
  3. foreach my $char (@chars) {
  4. #do something with $char
  5. }
Reply With Quote Quick reply to this message  
Join Date: Nov 2008
Posts: 70
Reputation: orwell84 is an unknown quantity at this point 
Solved Threads: 3
orwell84's Avatar
orwell84 orwell84 is offline Offline
Junior Poster in Training

Re: substr problem

 
0
  #3
Apr 25th, 2009
Thanks, that worked. I was making a binary to decimal converter. Here's the code if anyone's interested:
  1. #!usr/bin/perl -w
  2.  
  3. print "Binary number: \n";
  4. $bin = <STDIN>;
  5. chomp $bin;
  6. $dec = 0;
  7. $exp = (length($bin)) - 1;
  8. @bin = split(//,$bin);
  9. chomp @bin;
  10.  
  11. foreach $bit (@bin){
  12. $dec += $bit * (2 ** $exp);
  13. $exp--;
  14. }
  15. print "$dec\n";
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:




Views: 845 | Replies: 2
Thread Tools Search this Thread



Tag cloud for Perl
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC