微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在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会愉快地从数字转换为字符串,反之亦然.

原文地址:https://www.jb51.cc/Perl/171756.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐