http://www.perlmonks.org?node_id=1029996


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)