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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.