A Calculator might be a bad task as "one of your first programs", because parsing mathematical expressions is an advanced challenge, but you can do it in steps, getting better and better. First idea is getting operand,operator,operand as single unput:

chomp(my $left = <STDIN>); chomp(my $op = <STDIN>); chomp(my $right = <STDIN>); print $op eq '+' ? $left + $right : $op eq '-' ? $left - $right : $op eq '*' ? $left * $right : $op eq '/' ? $left / ($right||1) : "dunno operator '$op'", , "\n";

Next step is to read the whole thing in a one string:

chomp( my $expr = <STDIN> ); # and to parse it with simple split my ($left,$op,$right) = split /\s+/,$expr # next step is code of above

Sooner or later you'll want to replace the ?:?: .. chain with a hash:

my %operations = ( '+' => sub { (shift) + (shift) }, '-' => sub { (shift) - (shift) }, '*' => sub { (shift) * (shift) }, '/' => sub { (shift) / (shift||1) }, ); my ($left,$op,$right) = ...; #wherever you get them from print exists $operations{$op} ? $operations{$op}->($left,$right) : "dunno operator '$op'", "\n";

Next you want to verify the input using a regexp:

chomp(my $expr = <STDIN>); $expr =~ /(\d+)\s+([+-/*])\s+(\d+)/ or die "invalid input\n"; my ($left,$op,$right) = ($1,$2,$3); # ...

Then you'll find advanced regexps for numbers (see perlfaq4), Math::Expr, and finally Parse::RecDescent .

--
http://fruiture.de

In reply to Re: Inputing an Operator is it possible? by fruiture
in thread Inputing an Operator is it possible? by $Variable_B

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.