944,006 Members | Top Members by Rank

Ad:
  • Perl Discussion Thread
  • Marked Solved
  • Views: 1191
  • Perl RSS
Apr 18th, 2009
0

substr problem

Expand Post »
I'm having a problem with the substr function. I want it to be dynamic in a for loop as follows:
perl Syntax (Toggle Plain Text)
  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.
Similar Threads
Reputation Points: 17
Solved Threads: 5
Junior Poster
orwell84 is offline Offline
100 posts
since Nov 2008
Apr 18th, 2009
0

Re: substr problem

use split instead:

Perl Syntax (Toggle Plain Text)
  1. my $var = 'abcdefghijklmnop';
  2. my @chars = split(//,$var);
  3. foreach my $char (@chars) {
  4. #do something with $char
  5. }
Reputation Points: 246
Solved Threads: 67
Practically a Posting Shark
KevinADC is offline Offline
898 posts
since Mar 2006
Apr 25th, 2009
0

Re: substr problem

Thanks, that worked. I was making a binary to decimal converter. Here's the code if anyone's interested:
perl Syntax (Toggle Plain Text)
  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";
Reputation Points: 17
Solved Threads: 5
Junior Poster
orwell84 is offline Offline
100 posts
since Nov 2008

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Perl Forum Timeline: Using this perl code behind a router: this one is definitely a puzzle
Next Thread in Perl Forum Timeline: New to Perl HELP.





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC