Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Best guess for data type

by LanX (Canon)
on Apr 22, 2013 at 22:52 UTC ( #1029996=note: print w/ replies, xml ) Need Help??


in reply to Best guess for data type

> For example, given 100 numbers would guess that its a numerical array while mixed strings and numbers would return that the best data type is string.

depends on your definition of number, but I think this helps:

DB<160> @a=("1",0) => (1, 0) DB<161> if (grep { $_+0 ne $_ } @a) { "string" } else { "num" } => "num" DB<162> @a=("1 ",0,"") => ("1 ", 0, "") DB<163> if (grep { $_+0 ne $_ } @a) { "string" } else { "num" } => "string"

> I am thinking along the lines of what most statistical applications do when you load a CSV file and they try to guesstimate what data type each column is.

scalar grep returns a number, your free to check for thresholds.

DB<166> @a=("1 ",0,"") => ("1 ", 0, "") DB<167> scalar grep { $_+0 ne $_ } @a => 2 DB<168> (grep { $_+0 ne $_ } @a) > @a/2 => 1

update

you could also use Scalar::Util which is core

DB<186> use Scalar::Util qw/looks_like_number/ => 0 DB<187> grep { ! looks_like_number($_) } 0,"1","2 ", 3.14, " 4 ", 5e +55, "six" => "six"

please not that now strings like " 4 " are considered numbers!

As I said depends a lot on your definition... =)

Cheers Rolf

( addicted to the Perl Programming Language)


Comment on Re: Best guess for data type
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1029996]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (15)
As of 2014-09-23 17:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (233 votes), past polls