Printable Version of Topic

Click here to view this topic in its original format

HTMLHelp Forums _ Server-side Scripting _ Perl - String to Integer

Posted by: SteveD Dec 23 2006, 12:40 AM

I thought Perl would automatically convert strings to numbers, etc., based on the operator. However, I keep getting a warning message indicating it is confused.

I read a line in from a text file. The line has strings and integers. Everything works fine except the last element in the file is an integer. I'm guessing that since that also has the newline, chomp is making it a string. Then when I do a comparison on this value to a certain number, the warning says I have an uninitialized value at the > sign.

I tried doing a $int_var = $int_var + 0; thinking that would force it to a number but then I get an uninitialized value at + sign.

I took out the chomp command and that didn't help.

Isn't there a simple way to force a string to be an integer?

Posted by: Darin McGrew Dec 23 2006, 03:55 AM

QUOTE
I tried doing a $int_var = $int_var + 0; thinking that would force it to a number but then I get an uninitialized value at + sign.
Hmm... It sounds like something else is going on. I might have written $int_var += 0 ; or possibly $int_var *= 1 ; but that should make sure the $int_var is an integer. Not that it really matters until you use it in an expression, at which point it can be converted to an integer as necessary.

I suppose you could try adding a debugging print statement right before that point to see what value $int_var has.

Posted by: SteveD Dec 23 2006, 02:48 PM

I'm an old assembly programmer, but I changed my code to $int_val += 0; just to make it better and that seemed to fix the problem. Not sure why but if it works I'm happy.

Thanks for the help.
Steve

Posted by: Curtis Dec 28 2006, 05:32 AM

Wow, that is odd, I can't seem to recreate the problem (I know issue is solved, but I'm curious). Perl is indeed dynamically and loosely typed.

I even tried:

CODE
#!C:/Perl/bin/perl

use strict;
use warnings;

# Print errors to browser, rather than server 500 internal errors
use CGI::Carp qw/fatalsToBrowser/;
use Data::Dumper;

# Header
print "Content-Type: text/plain\r\n\r\n";

my $int_val = 'abc15';
#$int_val = $int_val + 0;

print Dumper($int_val) if ( $int_val < 20 );

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)