Here's another stab at a possible solution. A robust parser such as has been discussed by others would probably be better, but something like this may serve.
c:\@Work\Perl>perl -wMstrict -le "my $operators = '+-*/'; my %disp = map { $_ => eval qq{ sub { return \$_[0] $_ \$_[1] } } } split '', $operators ; my $int = qr{ [-+]? \d+ }xms; my $op = qr{ [\Q$operators\E] }xms; ;; my $t = 'foo 1 + 2 bar 34*56 baz 3- 4 and 56 /78 too'; ;; for my $s ($t, @ARGV) { print ''; print qq{'$s'}; $s =~ s{ ($int) \s* ($op) \s* ($int) }{ $disp{$2}->($1, $3) }xmsge; print qq{'$s'}; } " "x-3--4,-3++4" "foo+bar" 'foo 1 + 2 bar 34*56 baz 3- 4 and 56 /78 too' 'foo 3 bar 1904 baz -1 and 0.717948717948718 too' 'x-3--4,-3++4' 'x1,1' 'foo+bar' 'foo+bar'
... code to make you understand my problem ...
In this spirit, I was tempted to post only the code from the statement
my $t = 'foo 1 + 2 bar 34*56 baz 3- 4 and 56 /78 too';
on down and title it something like "code to make you understand my solution", but let's just say no more...
Update: For instance, the code above fails for something as simple as "1 + 2 + 3" which even a fairly simple parser could handle. But again, we don't know just what's really needed...
In reply to Re: converting from str to int
by AnomalousMonk
in thread converting from str to int
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |