在 Perl 中查找标量变量的数据类型 [英] Finding the data type of a scalar variable in Perl

查看:48
本文介绍了在 Perl 中查找标量变量的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受用户输入的函数.输入可能是整数、浮点数或字符串.我有三个重载函数,应该根据输入数据的数据类型调用它们.例如,如果用户输入一个整数(比如 100),则应该调用具有整数参数的函数.如果用户输入一个字符串(比如100"),则应该调用具有字符串参数的函数.

I have a function which accepts an input from the user. The input maybe an integer, a float or a string. I have three overloaded functions which should be called based on the DATA TYPE of the entered data. For example, if the user enters an integer (say 100), the function having integer parameter should be called. If the user enters a string (say "100") the function having the string parameter should be called.

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

So I need to find out the data type of the entered data. With regular expressions I am able to distinguish between an integer and a float (since I just need to find out the type, I wont prefer using the library provided at cpan.org), but I am not able to figure out how to differentiate an integer from a string. Perl treats "100" and 100 as the same? Is there any way to work around this problem?

推荐答案

来自 perldoc perldata:

标量不一定是一回事.没有地方可以将标量变量声明为字符串"类型、数字"类型、引用"类型或其他任何类型.由于标量的自动转换,返回标量的操作不需要关心(事实上,也不关心)它们的调用者是在寻找字符串、数字还是引用.Perl 是一种上下文多态语言,其标量可以是字符串、数字或引用(包括对象).尽管字符串和数字在几乎所有用途中都被视为几乎相同的东西,但引用是强类型、不可转换的指针,具有内置的引用计数和析构函数调用.

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 会根据上下文愉快地将数字转换为字符串,反之亦然.

So for integer scalars, you'll just need to decide ahead of time how you want to process them. Perl will cheerfully convert from a number to a string or vice versa depending on the context.

这篇关于在 Perl 中查找标量变量的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆