string 如何在 Perl 中将字符串转换为数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/288900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:20:06  来源:igfitidea点击:

How can I convert a string to a number in Perl?

stringperlfloating-point

提问by Anton

I have a string which holds a decimal value in it and I need to convert that string into a floating point variable. So an example of the string I have is "5.45" and I want a floating point equivalent so I can add .1 to it. I have searched around the internet, but I only see how to convert a string to an integer.

我有一个包含十进制值的字符串,我需要将该字符串转换为浮点变量。所以我拥有的字符串的一个例子是“5.45”,我想要一个等价的浮点数,这样我就可以将 .1 添加到它。我在互联网上搜索过,但我只看到如何将字符串转换为整数。

回答by Alnitak

You don't need to convert it at all:

您根本不需要转换它:

% perl -e 'print "5.45" + 0.1;'
5.55

回答by porquero

This is a simple solution:

这是一个简单的解决方案:

Example 1

示例 1

my $var1 = "123abc";
print $var1 + 0;

Result

结果

123

Example 2

示例 2

my $var2 = "abc123";
print $var2 + 0;

Result

结果

0

回答by brian d foy

Perl is a context-based language. It doesn't do its work according to the data you give it. Instead, it figures out how to treat the data based on the operators you use and the context in which you use them. If you do numbers sorts of things, you get numbers:

Perl 是一种基于上下文的语言。它不会根据您提供的数据完成其工作。相反,它会根据您使用的运算符和使用它们的上下文来确定如何处理数据。如果你做数字之类的事情,你会得到数字:

# numeric addition with strings:
my $sum = '5.45' + '0.01'; # 5.46

If you do strings sorts of things, you get strings:

如果你做字符串之类的事情,你会得到字符串:

# string replication with numbers:
my $string = ( 45/2 ) x 4; # "22.522.522.522.5"

Perl mostly figures out what to do and it's mostly right. Another way of saying the same thing is that Perl cares more about the verbs than it does the nouns.

Perl 主要知道要做什么,而且大部分是正确的。另一种说法是 Perl 更关心动词而不是名词。

Are you trying to do something and it isn't working?

您是否正在尝试做某事但它不起作用?

回答by Norm

Google lead me here while searching on the same question phill asked (sorting floats) so I figured it would be worth posting the answer despite the thread being kind of old. I'm new to perl and am still getting my head wrapped around it but brian d foy's statement "Perl cares more about the verbs than it does the nouns." above really hits the nail on the head. You don't need to convert the strings to floats before applying the sort. You need to tell the sort to sort the values as numbers and not strings. i.e.

谷歌在搜索 phill 提出的相同问题(排序浮点数)时将我带到这里,所以我认为尽管线程有点旧,但还是值得发布答案。我是 perl 的新手,仍然对它感到困惑,但是 brian d foy 的声明“Perl 更关心动词而不是名词。” 以上真是一针见血。在应用排序之前,您不需要将字符串转换为浮点数。您需要告诉排序将值排序为数字而不是字符串。IE

my @foo = ('1.2', '3.4', '2.1', '4.6');
my @foo_sort = sort {$a <=> $b} @foo;

See http://perldoc.perl.org/functions/sort.htmlfor more details on sort

有关排序的更多详细信息,请参阅http://perldoc.perl.org/functions/sort.html

回答by mccutchm

As I understand it int()is not intended as a 'cast' function for designating data type it's simply being (ab)used here to define the context as an arithmetic one. I've (ab)used (0+$val) in the past to ensure that $val is treated as a number.

据我了解,int()并不是用于指定数据类型的“强制转换”函数,它只是在这里(ab)用于将上下文定义为算术函数。我过去 (ab) 使用 (0+$val) 来确保 $val 被视为一个数字。

回答by indexless

$var += 0

probably what you want. Be warned however, if $var is string could not be converted to numeric, you'll get the error, and $var will be reset to 0:

可能是你想要的。但是请注意,如果 $var is string 无法转换为数字,您将收到错误消息,并且 $var将重置为 0

my $var = 'abc123';
print "var = $var\n";
$var += 0;
print "var = $var\n";

logs

日志

var = abc123
Argument "abc123" isn't numeric in addition (+) at test.pl line 7.
var = 0

回答by Rini

Perl really only has three types: scalars, arrays, and hashes. And even that distinction is arguable. ;) The way each variable is treated depends on what you do with it:

Perl 实际上只有三种类型:标量、数组和散列。甚至这种区别也是有争议的。;) 每个变量的处理方式取决于你用它做什么:

% perl -e "print 5.4 . 3.4;"
5.43.4


% perl -e "print '5.4' + '3.4';"
8.8

回答by Steffen Moeller

In comparisons it makes a difference if a scalar is a number of a string. And it is not always decidable. I can report a case where perl retrieved a float in "scientific" notation and used that same a few lines below in a comparison:

在比较中,如果标量是字符串的数字,则会有所不同。它并不总是可决定的。我可以报告一个案例,其中 perl 以“科学”符号检索浮点数,并在比较中使用相同的以下几行:

use strict;
....
next unless $line =~ /and your result is:\s*(.*)/;
my $val = ;
if ($val < 0.001) {
   print "this is small\n";
}

And here $valwas not interpreted as numeric for e.g. "2e-77"retrieved from $line. Adding 0 (or 0.0 for good ole C programmers) helped.

并且这里$val没有被解释为数字,例如"2e-77"$line. 添加 0(或 0.0 对于优秀的 ole C 程序员)有帮助。

回答by SzG

Perl is weakly typed and context based. Many scalars can be treated both as strings and numbers, depending on the operators you use. $a = 7*6; $b = 7x6; print "$a $b\n";
You get 42 777777.

Perl 是弱类型和基于上下文的。许多标量可以被视为字符串和数字,这取决于您使用的运算符。 $a = 7*6; $b = 7x6; print "$a $b\n";
你得到42 777777

There is a subtle difference, however. When you read numeric data from a text file into a data structure, and then view it with Data::Dumper, you'll notice that your numbers are quoted. Perl treats them internally as strings.
Read:$my_hash{$1} = $2 if /(.+)=(.+)\n/;.
Dump:'foo' => '42'

然而,有一个微妙的区别。当您将文本文件中的数字数据读入数据结构,然后使用 进行查看时Data::Dumper,您会注意到您的数字被引用了。Perl 在内部将它们视为字符串。
阅读:$my_hash{$1} = $2 if /(.+)=(.+)\n/;
倾倒:'foo' => '42'

If you want unquoted numbers in the dump:
Read:$my_hash{$1} = $2+0 if /(.+)=(.+)\n/;.
Dump:'foo' => 42

如果您想在转储中使用不带引号的数字:
阅读:$my_hash{$1} = $2+0 if /(.+)=(.+)\n/;
倾倒:'foo' => 42

After $2+0Perl notices that you've treated $2 as a number, because you used a numeric operator.

$2+0Perl 注意到您将 $2 视为数字之后,因为您使用了数字运算符。

I noticed this whilst trying to compare two hashes with Data::Dumper.

我在尝试将两个哈希与Data::Dumper.