【perl】数での比較と文字列での比較(例:5と14を文字列として比較するとどちらが大きいか)
#! /usr/bin/perl use strict; use warnings; my $x = 5; my $y = 14; if ($x >= $y){ print "$x >= $y\n"; }else{ print "$x < $y\n"; } #5の方が14より大きいと判定される。文字列として比較されているため。 #ge = greater than or equal to if ($x ge $y){ print "$x ge $y\n"; }else{ print "$x lt $y\n"; }
人間の私からしたら、「1,2,3…」は数字で、文字列とは「あいうえお…」をのことで、数字を文字列として見立てたことなんて記憶がある中ではないので変な感じ。数字を文字列として比較するときは、数学記号を英語に置き換えて、その頭文字を取ればいい。今回使ったgeのほかには、以下のような感じ。
== eq (equal) != ne (not equal to) < lt (less than to) > gt (greater than to) <= le (less than or equal to) >= ge (greater than or equal to) <=> cmp (compare)
compareのときは、等しいなら0、左辺が右辺より小さいなら-1、大きいなら1が返る。