Wednesday, May 12, 2010

Jr. High Math - Perl to the rescue

My daughter needed a calculator to check square roots last night.  I couldn't believe it - we didn't have one!  Well, I had my beloved HP 15C from engineering school days.  RPN is cool - right?!  Yeah, you can imagine how that went over.  So, then I grabbed a slide rule.  I know!  You guessed it - worse reaction than RPN.  So then I grabbed her Dell netbook, which was running Ubuntu Linux , and wrote a Perl hack that was basically

   #!/usr/bin/perl
   print "Enter a number\n";
   $number = stdin;
   chomp $number;
   $root = sqrt $number;
   print "The square root of $number is $root\n";

Ha!  It worked and she used it.  Perl to the rescue!

4 comments:

  1. Oops. Looks like line three needed the angle brackets around stdin escaped.

    ReplyDelete
  2. use 5.010;

    say "Enter your number: ";
    chomp( my $number = );
    my $root = sqrt $number;
    say "The square root of $number = $root";

    ReplyDelete
  3. Actually, you don't need the second variable; instead of these two lines:

    my $root = sqrt $number;
    say "The square root of $number = $root";

    The following single line would be better:

    say "The square root of $number = ", sqrt $number;

    And for a proper program, you might want to include the ability to get the root of as many numbers as you like, plus add checking for invalid numbers:

    #!/usr/bin/perl
    use warnings;
    use strict;
    use 5.010;

    # This program calculates square roots for user-defined (and valid) numbers:

    say "Enter a number, or press to exit: ";

    {
    chomp( my $number = );

    if ( $number =~ /^\s*$/ ) {
    say "Have a nice day!";
    last;
    }

    elsif ( $number =~ /^-/ ) {
    say "Sorry, we can't take the square root of a negative number!";
    say "Try a postive number this time.. ";
    redo;
    }

    elsif ( $number =~ /\D+/ ) {
    say "That's not a valid number! Please try again: ";
    redo;
    }

    else {
    say "The square root of $number = ", sqrt $number;
    say "next number, please: ";
    redo;
    }

    }

    ReplyDelete
  4. Sorry for the multiple comments, but obviously STDIN inside angle brackets was deleted from my two previous comments.

    ReplyDelete