Numeric Testing
The
final utility function supplied by DBI
that we’ll look at is quite a curious one called
looks_like_number()
. This function quite simply tells you
whether or not a value looks like a number or not.
looks_like_number() operates by taking a list of
values as an argument and returns a new array signifying whether or
not the corresponding value within the original array was a number,
not a number, or undefined.
This may seem rather a curious thing to want to do, but in the case
of handling large quantities of data, it’s useful for working
out which values might need to have their quotes escaped via the
quote()
method.
The returned array will contain the same number of values as the original data array, with the elements containing one of three values signifying the following:
true The original value is a number. false The original value is not a number. undef The original value is empty or undefined.
The following example illustrates how this process works:
#!/usr/bin/perl -w # # ch04/util/lookslike1: Tests out the DBI::looks_like_number() function. # use DBI; ### Declare a list of values my @values = ( 333, 'Choronzon', 'Tim', undef, 'Alligator', 1234.34, 'Linda', 0x0F, '0x0F', 'Larry Wall' ); ### Check to see which are numbers! my @areNumbers = DBI::looks_like_number( @values ); for (my $i = 0; $i < @values; ++$i ) { my $value = (defined $values[$i]) ? $values[$i] : "undef"; print "values[$i] -> $value "; if ( defined $areNumbers[$i] ) { if ( $areNumbers[$i] ) { ...