在Perl中查找标量变量的数据类型

我有一个接受用户输入的功能.输入可以是整数,浮点数或字符串.我有三个重载函数,应根据输入数据的DATA TYPE调用.例如,如果用户输入整数(例如100),则应调用具有整数参数的函数.如果用户输入字符串(例如“100”),则应调用具有字符串参数的函数.

所以我需要找出输入数据的数据类型.使用正则表达式,我能够区分整数和浮点数(因为我只需要找出类型,我不喜欢使用cpan.org提供的库),但我无法弄清楚如何区分字符串中的整数. Perl对待“100”和100对待?有没有办法解决这个问题?

解决方法

来自perldoc perldata:

Scalars aren’t necessarily one thing or another. There’s no place to declare a scalar variable to be of type “string”,type “number”,type “reference”,or anything else. Because of the automatic conversion of scalars,operations that return scalars don’t need to care (and in fact,cannot care) whether their caller is looking for a string,a number,or a reference. Perl is a contextually polymorphic language whose scalars can be strings,numbers,or references (which includes objects). Although strings and numbers are considered pretty much the same thing for nearly all purposes,references are strongly-typed,uncastable pointers with builtin reference-counting and destructor invocation.

因此,对于整数标量,您只需要提前决定如何处理它们.根据上下文,Perl会愉快地从数字转换为字符串,反之亦然.

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...