# Perl6 notes: Numbers and strings

Posted on April 29, 2023
Tags: ,

This set of notes contains a summary of what I have learned from the book Learning Perl6.

# Integer

## Literals

# 111 in base 2
:2<111>

# Same as 9875
98_75


# Other numerical types

Similar to Scheme, Perl6 implements a numerical tower. Most importantly, in cases where applicable, Perl6 will produce rational numbers instead of floating points.

<1/3> # 0.333333
<1/3>.^mro # ((Rat) (Cool) (Any) (Mu))


<1/3> is rendered as a floating point, but there is no loss of precision in the internal representation.

Rat is not arbitrary precision. FatRat is needed if the denominator needs to be more than a $$64$$-bit integer.

FatRat.new: 1, 3
FatRat.new( 1, 3) # Same thing as above
<1/3>.FatRat # Cast from a rational literal


# Smart matching

# Similar to Java's instanceof
1 ~~ Int # True

1 ~~ Str # False

# Despite its look, ~~ is not an equivalence relation
Int ~~ 1 # False

# Dispatch based on types
# given uses ~~ to match the scrutinee
sub break-parametricity (Any $v) { given$v {
when Int { $v+1 } when Str {$v ~ "!"}
default {False}
}
}

break-parametricity(10) # 11
break-parametricity("hey") # hey!


# Block to expression

The do keyword is similar to the begin keyword from scheme.

# Evaluates to 201
1 + do {
my Int $x = 0;$x += 100;
say $num+1  # Interpolation my Str$hello := "hello";
"$hello world" # hello world qq/{$hello ~ " world"}/ # hello world
Q :qq/{$hello ~ " world"}/ # same as above # Interpolate in a single quote q/\qq[{$hello ~ " world"}]/ # hello world

# Uninterpolate in a double quote
qq/\q[{$hello ~ " world"}]/ # {$hello ~ " world"}


Consult the fancier quoting section from Learning Perl6 for more adverb options.

# Run commands

chomp Q :x/uname/ # Linux
chomp Qx /uname/ #Same thing