code

Perl에서 문자열을 숫자로 어떻게 변환 할 수 있습니까?

codestyles 2020. 10. 4. 11:18
반응형

Perl에서 문자열을 숫자로 어떻게 변환 할 수 있습니까?


숫자를 포함하는 문자열을 Perl에서 숫자 값으로 어떻게 변환합니까?


변환 할 필요가 전혀 없습니다.

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

이것은 간단한 해결책입니다.

예 1

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

결과

123

예 2

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

결과

0

Perl은 컨텍스트 기반 언어입니다. 사용자가 제공 한 데이터에 따라 작업을 수행하지 않습니다. 대신 사용하는 연산자와 사용하는 컨텍스트를 기반으로 데이터를 처리하는 방법을 알아냅니다. 숫자와 같은 일을하면 숫자를 얻게됩니다.

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

문자열과 같은 일을하면 문자열을 얻습니다.

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

Perl은 대부분 무엇을해야하는지 알아 내고 대부분 옳습니다. 같은 말을하는 또 다른 방법은 Perl이 명사보다 동사에 더 신경을 쓴다는 것입니다.

무언가를하려고하는데 작동하지 않습니까?


Google은 필이 묻는 동일한 질문 (수레 정렬)을 검색하는 동안 나를 여기로 안내하여 스레드가 오래 되었음에도 불구하고 답변을 게시 할 가치가 있다고 생각했습니다. 나는 펄을 처음 접했고 여전히 내 머리를 감싸고 있지만 brian d foy의 말 "Perl은 명사보다 동사에 더 신경을 쓴다." 위는 정말 머리에 못을 친다. 정렬을 적용하기 전에 문자열을 부동 소수점으로 변환 할 필요가 없습니다. 값을 문자열이 아닌 숫자로 정렬하도록 정렬에 지시해야합니다.

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

정렬에 대한 자세한 내용 http://perldoc.perl.org/functions/sort.html 을 참조하십시오.


내가 이해했듯이 int () 는 데이터 유형을 지정하는 '캐스트'함수로 의도되지 않았으며 여기에서 컨텍스트를 산술로 정의하는 데 사용됩니다. $ val이 숫자로 취급되도록 과거에 (ab) (0 + $ val)을 사용했습니다.


$var += 0

아마도 당신이 원하는 것입니다. 그러나 $ var가 문자열이면 숫자로 변환 할 수없는 경우 오류가 발생하고 $ var 는 0으로 재설정됩니다 .

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

로그

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

Perl에는 실제로 스칼라, 배열 및 해시의 세 가지 유형 만 있습니다. 그리고 그 구별조차도 논쟁의 여지가 있습니다. ;) 각 변수가 처리되는 방식은 사용하는 작업에 따라 다릅니다.

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


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

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:

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

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


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.

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'

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

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

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

참고URL : https://stackoverflow.com/questions/288900/how-can-i-convert-a-string-to-a-number-in-perl

반응형