LoginSignup
1
1

More than 5 years have passed since last update.

Perl6の Context Forcing Operators

Posted at

こんばんは :whale2:
Perl 6 Advent Calendar 2015の、えっと…6日目ですね。

String context

例題・Int型の変数に入った123456789を、Str型の変数に代入したい。

異常系
use v6;

my Str $string;
my Int $integer = 123456789;

$string = $integer; # エラー
                    # Type check failed in assignment to $string; expected Str but got Int

こんな時は、~を使ってString contextに変換します。

正常系
use v6;

my Str $string;
my Int $integer = 123456789;

$string = ~$integer; # force string context

$string.perl.say; #=> "123456789"

.perlは、Perl5でいうところのData::Dumperの親戚です。(ざっくり)
Str型の変数$stringに文字列"123456789"が代入されました。

Boolean context

Perlの数値型の評価は0がFalseで、それ以外がTrueです。
?でBool型の変換、!で否定ができます。

use v6;

my Bool $boolean;
my Real $number = 0.0;

$boolean = ?$number;
$boolean.perl.say;      #=> Bool::False

$boolean = !$number;
$boolean.perl.say;      #=> Bool::True

文字列の場合は、''(空文字)がFalseで、それ以外がTrueでしたよね。

use v6;

my Bool $boolean;
my Str  $string = '';

$boolean = ?$string;
$boolean.perl.say;      #=> Bool::False

$boolean = !$string;
$boolean.perl.say;      #=> Bool::True

Numeric Context

文字列型から数値型の変換は+-で行います。

use v6;

my Str $string = '1/3';
my Rat $rational;

$rational = +$string;
$rational.perl.say; #=> <1/3>

$rational = -$string;
$rational.say;      #=> -0.333333

使い所

use v6;

my $text = 'hoge0123456789';

# 数値以外の文字列で最初にマッチするもの
my $string = ~($text ~~ /\D+/);

# 大文字小文字区別しないで、先頭にHOGEが含まれているかどうか
my $truth  = ?($text ~~ m:ignorecase/^HOGE/);

# 数字が何文字含まれているのか
my $count  = +($text ~~ m:global/\d/);

$string.say; #=> hoge
$truth.say;  #=> True
$count.say;  #=> 10

おわりです。

おわりに

明日のAdvent Calendar執筆してくださる方募集です。
よろしくおねがいします。

参考と注釈

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1