I'm having a problem with the substr function. I want it to be dynamic in a for loop as follows:

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.

use split instead:

my $var = 'abcdefghijklmnop';
my @chars = split(//,$var);
foreach my $char (@chars) {
   #do something with $char
}

Thanks, that worked. I was making a binary to decimal converter. Here's the code if anyone's interested:

#!usr/bin/perl -w

print "Binary number: \n";
$bin = <STDIN>;
chomp $bin;
$dec = 0;
$exp = (length($bin)) - 1;
@bin = split(//,$bin);
chomp @bin;

foreach $bit (@bin){
	$dec += $bit * (2 ** $exp);
	$exp--;
	}
print "$dec\n";
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.