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

标签 perl

我有一个接受用户输入的函数。输入可能是整数、浮点数或字符串。我有三个重载函数,应该根据输入数据的数据类型调用它们。例如,如果用户输入一个整数(比如 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 会根据上下文愉快地从数字转换为字符串,反之亦然。

关于perl - 在 Perl 中查找标量变量的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6361696/

相关文章:

python - 使用perl或python将阿拉伯字符 "ا"替换为一个单词中的 "a",但替换为另一个单词中的 "ә"

Perl 继承 - 子程序覆盖

Perl 打包消息?

perl - 从 .perldb init 文件设置断点

perl - 使用 Test::More 和 Test::Deep 打印失败的子测试

Perl Mechanize 遇到错误 : failed connecting to "localhost", 端口 4242 : so what?

html - 你如何在 Perl 中处理格式错误的 HTML?

perl - 替换多行纯文本

objective-c - C/Objective-C 中的 Perl 中的 "<=>"运算符是否有替代方案?

perl - 如何在重负载下对 IO 绑定(bind)的 Perl Web 应用程序进行基准测试和分析?