in reply to Test for number or string

I had a feeling someone would ask..
I want to create a backup .txt file for an mySQL database table which can be easily uploaded via a custom script. The script requires that strings be single quoted, but not the numbers. One or more of the fields could contain an all numeric field that I want to save as a quoted string.
ie: zip=94566 or 94566-1234.
The .txt file is loaded into the database using..
INSERT INTO table VALUES($fileline);

Replies are listed 'Best First'.
Re: Re: Test for number or string
by LameNerd (Hermit) on May 03, 2003 at 00:06 UTC
    If you are using DBI use placeholders. You might find this node helpful.
Re: Re: Test for number or string
by Anonymous Monk on May 03, 2003 at 00:39 UTC

    Apart from that using placeholders is almost certainly the way to go, I think that your reasoning is slightly flawed.

    Either you know that this $var contains the value that is maintained as a string field, or you don't. Perl doesn't store the quotes internally and whenever you load a variable, the initial value of the variable is always a string. It doesn't get converted to its binary form until you use it in a numeric context, at which point perl will convert the ascii representation to the binary numeric form. If you then imediately use it in a string context, perl will convert it back. Any simple test you tried to apply for either form is going to always be true because perl will supply the form you are asking for.

    You don't say at which point in the process you are trying to make the determination.

    When you are writing it to the text file, or when you read it back?

    In the former case, you should be able to determine the type of the field from the table schema.

    In the latter case, assuming you wrote the string quoted, you could simply not strip them off when you read the file in, and then you would know which was which. ie.

    if( substr($var, 0, 1) eq "'" ) { print "It's a string\n" }

    HTH?

      In the former case, you should be able to determine the type of the field from the table schema.
      I could indeed do that (see below) but I was trying to simplify things. I tried INSERTing into the database without the quotes and it would not save the data. I do understand your point regarding Perl's handling of strings and numbers.
        PostgreSQL is nice in that you can put quotes even if you are inserting a number.