On Mon, Apr 23, 2001 at 11:38:42AM -0400, David Gilden wrote:
: Is there a better way of doing this?

Dave, here is my take on it, hopefully commented well:

#!/usr/local/bin/perl -w
use strict;
$|++;

while ( <DATA> ) {
  chomp; 
  print( &validate( $_ ) ? 'valid entry' : 'try again punk' );
  print "\n";
}

sub validate {
  my $currency = shift;

  # return false if we have an empty string or the string is just '$'.
  return 0 unless length( $currency ) > 0 && $currency ne '$';

  $currency =~ m<
                 ^      # The beginning of the string
                 \$?    # We may have a $ sign, we may not
                 \s*    # We may encounter some space here
                 \d*    # We may nave a numerator but could just have '.50'
                 (?:\.?\d{1,2})? # and we might have a denominator
                 $      # The end of the string
                >x ? 1: 0; # true if match succeeded, false otherwise
}

__DATA__

$
$ 4.000
0
$5
$ 5
$ 5.0
$5.00
5.00
.4
$.60


The output from this program should be:

try again punk
try again punk
try again punk
valid entry
valid entry
valid entry
valid entry
valid entry
valid entry
valid entry
valid entry

which is what I'd expect.  I'm sure this won't work in all cased but
it handles a few more than your original post.

Enjoy!


: Thanks!
: Dave
: ----
: 
: 
: if ($in{'price'} eq "") {print '<font color="red">&#8226; Missing</font> '; }  
:  elsif (&checkPrice($in{'price'})) {
:   print '<font color="red">&#8226; Wrong Format</font>';
: }
: 
: ....
: 
: 
: sub checkPrice{
: 
: if ($_[0] =~ /\$?(\d*)(\.\d{0,2})?/) {
: return 1; 
:     } else {
: return 0;
:     }
: 
: }
: 
: 
: Allowable input: 
: $1
: $1.50
: 2
: .50
: $.50
: -----
: Not allowable input: 
: a
: $5a
: $e.40
: ------

-- 
Casey West

Reply via email to