Ronen Kfir <mailto:[EMAIL PROTECTED]> asked:
> The following script meant to calculate simple math drills,
> such as 5 *
> 9 or 4 + 3, written in one line. What I cannot comprehend is the lines
> marked with ---. What do they do? Why is there a "0 < index..."
That looks like somebody wrote a C program in Perl. (S)he
is using (r)index and substr to pluck apart the the input.
The "0 < index ..." construct is basically there to determine
wether the operator was a + or a *. Writing the constant on
the left hand in a comparison is a fairly common way to find
a missing "=" in an numerical eqality check - if you want to
check wether $a is 0, then the typo "0 = $a" will produce an
error, while the assignment "$a = 0" will most likely be
a nasty bug.
> $line = <STDIN>;
> chomp $line;
>
> $first_space = index($line , " ");
> $a = substr($line, 0, $first_space);
>
> $last_space = rindex($line , " ");
> $b = substr($line, $last_space+1);
>
>
> --- if (0 < index($line, "*")) {
> print $a * $b, "\n";
> }
> --- if (0 < index($line, "+")) {
> print $a + $b, "\n";
> }
Off the top of my head I'd suggest a different approach:
#!/usr/bin/perl -w
use strict;
# I like to read my test cases from the file itself
while( defined( my $line = <DATA> ) ){
# while has put the line in $_ for us
# this is also the variable that many
# functions act on by default
# remove all whitespace from the line
$line =~ s/\s//g;
# see if the line we read matches our
# pattern. If it does, we print the
# formula and the result.
# The Pattern assigns the following
# variables if it matches:
# $1 = the whole shebanf
# $2 = left operand ( optional minus, at least one digit
# $3 = operator (one of +, -, *, / )
# $4 = right operand
if( $line =~ /((-?\d+)([-+*\/])(-?\d+))/ ){
print "$2 $3 $4 = " . eval( $1 ) . "\n";
}
}
__DATA__
1+1
3 + 7
2 * 3
6 - 8
If you like oneliners, you could always write that as
perl -ne 's/\s//g;/((-?\d+)([-+*\/])(-?\d+))/&&print "$2 $3 $4 =
".eval($1)."\n"'
HTH,
Thomas
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]