On Tue, 15 Feb 2005, John W. Krahn wrote: > Oliver Fuchs wrote: > >Hi, > > Hello, > > >I am a very beginner to perl so may be this question is stupid or too low > >leveled then please ignore. > > > >I tried to wright a little calculator in perl - nothing difficult - very > >simple: > > > >#!/usr/bin/perl -w > > > >print "First value: "; > >chomp ($value1=<STDIN>); > >print "Second value: "; > >chomp ($value2=<STDIN>); > >print "What operator (+ - * /)? "; > >chomp ($operator=<STDIN>); > >if ($operator eq "+") { > > print ($value1 + $value2, "\n"); > > } elsif ($operator eq "-") { > > print ($value1 - $value2, "\n"); > > } elsif ($operator eq "*") { > > print ($value1 * $value2, "\n"); > > } elsif ($operator eq "/") { > > print ($value1 / $value2, "\n"); > > } else { > > print "Keep it simple \n"; > > } > > You could do something like this: > > > #!/usr/bin/perl -w > use strict; > > my %calc = ( > '+' => sub { return $_[0] + $_[1] }, > '-' => sub { return $_[0] - $_[1] }, > '*' => sub { return $_[0] * $_[1] }, > '/' => sub { return $_[0] / $_[1] }, > ); > > print 'First value: '; > chomp( my $value1 = <STDIN> ); > print 'Second value: '; > chomp( my $value2 = <STDIN> ); > print 'What operator (+ - * /)? '; > chomp( my $operator = <STDIN> ); > > if ( exists $calc{ $operator } ) { > print $calc{ $operator }->( $value1, $value2 ), "\n"; > } > else { > print "The operator '$operator' does not exist.\n"; > } > >
Hi, thanks for that (looks better than mine). > >Originell I tried to put the operator from <STDIN> directly to print like > >this: > > > >[...] > >print "First value: "; > >chomp ($value1=<STDIN>; > >print "Second Value: "; > >chomp ($value2=<STDIN>; > >print "Operator: "; > >chomp ($value3=<STDIN>; > > > >print ($value1 $value3 $value2, "\n"); > > > >But that was malfaunctioning. Is there a way to put the STDIN for the > >operator directly in the print line or do I always have to keep it that > >long > >winded? > > You could always use the eval() function: > > perldoc -f eval Thanks again. It worked for me with: #!/usr/bin/perl -w print "Enter a expression to calculate:\n"; chomp($expression=<STDIN>); print eval($expression), "\n"; Oliver -- ... don't touch the bang bang fruit -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>