Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: String/Numeric Manipulation

by Random_Walk (Prior)
on Oct 07, 2004 at 17:17 UTC ( #397379=note: print w/replies, xml ) Need Help??


in reply to String/Numeric Manipulation

The while test on the value of days is made after the conversion to seconds is done so when you enter q you are trying to convert it to seconds. you could do a few things, here is one that keeps a while loop...

#!/usr/local/bin/perl -w use strict; while (1) { print "Please enter a single positive integer that represents a number of da +ys, that you wish to convert into seconds. ,(enter q to quit): "; chomp (my $days = <STDIN>); $days =~ s/\+//; # allow them to enter +12 if ($days eq "q") { last; } elsif (($days =~ /[^\d]/) or ($days eq "")) { # days contains an non digit character or is empty print "\n!!! You must enter a positive integer.\n\n"; } else { my $seconds = $days * 86400; my $plural = ($days == 1) ? '' : 's'; print "\n$days day$plural = $seconds seconds.\n\n"; } } print "Goodbye\!\n\n";

update to catch entry of 0

Change the elsif check to this if you want to prevent them from entering zero days
} elsif (($days =~ /[^\d]/) or (not $days)) {

Cheers,
R.

Replies are listed 'Best First'.
Re^2: String/Numeric Manipulation
by Elgon (Curate) on Oct 07, 2004 at 18:56 UTC

    Random_Walk,

    A minor nit. If I've understood the code correctly, you've used a substitution...

    $days = s/+//;

    ...where a transliteration would be "better"...

    $days = tr/+//d;    # Note transobliteration modifier

    ...and a lot faster (not that this is really an issue in this case.)Unless you wanted to allow only a leading + in which case...

    $days = s/^+//;

    Elgon

    It is better wither to be silent, or to say things of more value than silence. Sooner throw a pearl at hazard than an idle or useless word; and do not say a little in many words, but a great deal in a few.

    Pythagoras (582 BC - 507 BC)

      You are right tr would have been more efficient for what I did but I really should have put s/^+//; to follow the principle of least surprise so that 2+3 would be rejected rather than converted to 23

      Cheers,
      R.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://397379]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2022-01-20 10:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (56 votes). Check out past polls.

    Notices?