gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:06:24 24 4
gpt4 key购买 nike

我有一个接受用户输入的函数。输入可能是整数、浮点数或字符串。我有三个重载函数,应该根据输入数据的数据类型调用它们。例如,如果用户输入一个整数(比如 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com