アプリ版:「スタンプのみでお礼する」機能のリリースについて

ある文字列からsubstrで3桁の数値を切り取り、計算に使いたいのですがゼロ詰めの数値の場合8進数になると思っていたのですが、文字列の場合は10進数の数値になります。
これは仕様でしょうか?

perlは型がないので、AもBもCも同じ値だと思っていましたが、
そのあたりについて詳しい方、違いを知っている方教えて頂けますか?

#-- A --
my $s = "007008009010";
print int( substr($s, 0, 3) ) . "\n";
print int( substr($s, 3, 3) ) . "\n";
print int( substr($s, 6, 3) ) . "\n";
print int( substr($s, 9, 3) ) . "\n";

print;

#-- B --
print int("007") . "\n";
print int("008") . "\n";
print int("009") . "\n";
print int("010") . "\n";

print;

#-- C --
print int(007) . "\n"; # 7
#print int(008) . "\n";
#print int(009) . "\n";
print int(010) . "\n"; # 8

A 回答 (2件)

仕様です。


詳しくは添付のドキュメント perldata.pod の
Scalar value constructors の項を参照してください。

Hexadecimal, octal, or binary, representations in string literals
(e.g. '0xff') are not automatically converted to their integer representation. The hex() and oct() functions make these
conversions for you. See hex in the perlfunc manpage and oct in
the perlfunc manpage for more details.

参考までに、oct関数に十六進表記文字列や二進表記文字列を食わせても
正しく変換してくれます。
ただし、0x, 0bが前置されていなければなりません。
    • good
    • 0

リテラルとしてプログラム中に陽に書いたときにだけ 8進数として扱う仕様のようです. 2進数や 16進数も同様みたい. oct で整

数に変換すれば OK かも.
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!