David said:
Quite new to Perl and I have a really simple question
How can I tell if a scalar contains a string or a value?
You mean string or a number. You could use regular expressions as suggested
by others.
One thing that no-one's yet mentioned, at least when I started writing this,
is the Scalar::Util module. I'm not sure about any other versions of Perl
but if you are running Active State Perl, you'll already have the module.
Here's how to determine if the first command-line argument is numeric:
use strict;
use warnings;
use English;
use Scalar::Util qw(looks_like_number);
local $OUTPUT_RECORD_SEPARATOR = "\n"; # Auto-print new-lines after prints.
my $scalar = $ARGV[0];
if(not defined $scalar)
{ # User didn't give any argument at all.
print "Please enter something after $PROGRAM_NAME.";
} # if
elsif(looks_like_number $scalar)
{ # We're dealing with a number here.
print "$scalar looks like a number to me.";
} # elsif
else
{ # Not a number => (NaN)
print "$scalar - that's no number.";
} # else
Points worthy of note:
1. The qw operator makes a list out of space delimited items this time a
single scalar. It follows the use statement and is not separated by a comma.
That idiom can be used to export function names directly in your name space.
If you didn't include the qw bit you would have to say:
Scalar::Util::looks_like_number()
which reminds me of Java in a negative way.
2. The English module let's one use readable variable names such as
$INPUT_RECORD_SEPARATOR. Here we've redefined the output record separator to
give a new-line after each print statement (output record or line if you
will). This ensures output behavior typical of DOS programs, that is two
line breaks before the prompt c:\> or whatever.
3. The looks_like_number function seems to work very well and might have a
faster version coded in C. SO I see no reason for having to match regular
expressions against numberness if any kind of number will do. IF you are
looking for particular kinds of numbers or numbers having certain properties
things will be different.
Hope this can be of help.