翻譯自 perl6maven.com
exit,warn,die
exit
#!/usr/bin/env perl6
use v6;
say "hello";
exit;
say "world"; # 這句不會執行了
#!/usr/bin/env perl6
use v6;
warn "This is a warning"; # 打印警告,帶行號
say "Hello World";
die
#!/usr/bin/env perl6
use v6;
say "Before calling die";
die "This will kill the script";
say "This will not show up";
Hello World
Hello World
使用關鍵字 say打印出字符串,并在字符串結尾自動添加一個換行符。字符串被雙引號包裹住。Perl 6 中語句以分號結束。
examples/intro/hello_world.p6
#!/usr/bin/env perl6
use v6;
say "Hello Perl 6 World";
同樣地, OOP 風格:
examples/intro/hello_world_oop.p6
#!/usr/bin/env perl6
use v6;
"Hello again Perl 6 World".say;
你可以鍵入 perl6 hello_world.p6 或 perl6 hello_world_oop.p6 中的任意一個.
實際上你甚至不需要所有3行,下面這個例子同樣有效,如果你這樣寫 perl6 hello_world_bare.p6 .
examples/intro/hello_world_bare.p6
say "Hello Perl 6 World";
sh-bang 行- 只在Unix/Linux下使用
文件后綴
盡管不是必須的,我使用文件后綴p6來表明這是個Perl 6 腳本。有些人只是使用常規的pl后綴,而實際上在UNIX 系統中這沒有什么不可。只是在有些編輯器是基于它們的文件后綴名來高亮語法時才顯得必要。
use v6;
這一行告訴perl下面的代碼需要Perl 6 或更高版本。如果你使用perl6來運行,這段代碼也會正確運行。但在Perl5下運行會有迷惑。例如 perl hell_world_bare.p6 輸出如下:
examples/intro/hello_world_bare.err
String found where operator expected at books/examples/intro/hello_world_bare.p6 line 1, near "say "Hello Perl 6 World""
(Do you need to predeclare say?)
syntax error at books/examples/intro/hello_world_bare.p6 line 1, near "say "Hello Perl 6 World""
Execution of books/examples/intro/hello_world_bare.p6 aborted due to compilation errors.
如果代碼中使用了use v6,但是使用perl 5 來運行的話,會發生什么?
perl hello_world.p6 輸出如下:
examples/intro/hello_world.err
Perl v6.0.0 required--this is only v5.14.2, stopped at books/examples/intro/hello_world.p6 line 2.
BEGIN failed--compilation aborted at books/examples/intro/hello_world.p6 line 2.
現在問題更清晰了 (Though it would be nice if the error message printed by perl 5 was something like: This code requires Perl v6.0.0. You ran it using v5.14.2.
given-when 結構
#!/usr/bin/env perl6
use v6;
my $a = prompt "Number:";
my $operator = prompt "Operator: [+-*/]:";
my $b = prompt "Number:";
given $operator {
when "+" { say $a + $b; }
when "-" { say $a - $b; }
when "*" { say $a * $b; }
when "/" { say $a / $b; }
default { say "Invalid operator $operator"; }
}
標量變量
字符串可以存儲在所謂的標量變量中。每個標量變量以符號 $ 開頭,后面跟著字母數字、單詞、下劃線和破折號。在第一次使用這種標量之前,我們必須使用 my 關鍵字 聲明它。
my $this_is_a_variable;
my $ThisIsAnotherVariableBut WeDontLikeItSoMuch;
my $this-is-a-variable;
變量是大小寫敏感的。
my $h;
my $H;
#!/usr/bin/env perl6
use v6;
my $greeting = "Hello World";
say $greeting;
my $Gábor-was-born-in = 'Hungary';
say $Gábor-was-born-in;
默認地,標量變量沒有特定的類型,但是隨后我們會看到,怎樣限制一個標量讓其能容納一個數字或任何其它類型。
聲明一個變量時也可不用初始化它的值: my $x;
在這種情況下,該變量的值為Any()
,也就是還沒被定義。
if 語句
你可以使用if 語句和其中之一的比較操作符來比較兩個值或標量變量。
#!/usr/bin/env perl6
use v6;
my $age = 23;
if $age > 18 {
say "You can vote in most countries.";
}
其他類型的 if 語句
if COND {
}
if COND {
} else {
}
if COND {
} elsif COND {
} elsif COND {
} else {
}
Perl 6 的散列
散列(也叫做關聯數組)是一列鍵值對,其中,鍵是唯一的字符串,鍵值可以是任意值。
散列以 % 符號開始。
#!/usr/bin/env perl6
use v6;
my %user_a = "fname", "Foo", "lname", "Bar";
my %user_b =
"fname" => "Foo",
"lname" => "Bar",
;
say %user_a{"fname"};
%user_a{"email"} = " foo@bar.com ";
say %user_a{"email"};
say %user_b;
輸出:
Foo
foo@bar.com
Bar
從散列中取回數據
#!/usr/bin/env perl6
use v6;
my %user =
"fname" => "Foo",
"lname" => "Bar",
"email" => " foo@bar.com ",
;
for %user.keys.sort -> $key {
say "$key %user{$key}";
}
輸出
email foo@bar.com
fname Foo
lname Bar
多維散列
#!/usr/bin/env perl6
use v6;
my %xml;
%xml[0] = 'Foo';
%xml[1] = 'Bar';
say %xml.perl;
輸出:
("person" => ["Foo", "Bar"]).hash
計算字數
#!/usr/bin/env perl6
use v6;
my $filename = 'examples/words.txt';
my %counter;
my $fh = open $filename;
for $fh.lines -> $line {
my @words = split /\s+/, $line;
for @words -> $word {
%counter{$word}++;
}
}
for %counter.keys.sort -> $word {
say "$word {%counter{$word}}";
}
回顧
#!/usr/bin/env perl6
use v6;
# 創建散列
my %h1 = first => '1st', second => '2nd';
if %h1{'first'}.defined {
say "the value of 'first' is defined";
}
if %h1.defined {
say "the value of 'second' is defined";
}
if %h1.exists('first') {
say "the key 'first' exists in h2";
}
say %h1.exists('third') ?? "third exists" !! "third does not exist";
say %h1;
say %h1;
# TODO hash with fixed keys not implemented yet
#my %h2{'a', 'b'} = ('A', 'B');
#say %h2.delete('a');
#say %h2.delete('a');
輸出:
the value of 'first' is defined
the value of 'second' is defined
the key 'first' exists in h2
third does not exist
1st
2nd
slurp
#!/usr/bin/env perl6
use v6;
my $filename = 'examples/phonebook.txt';
my @lines = lines $filename.IO;
for @lines -> $line {
say "L: $line";
}
#my %phonebook = map {split ",", $_}, @lines;
#my %phonebook = map {$_.comb(/\w+/)}, @lines;
my %phonebook = slurp($filename).comb(/\w+/);
my $name = prompt "Name:";
say %phonebook{$name};
輸出:
Foo,123
Bar,78
Baz,12321
kv
#!/usr/bin/env perl6
use v6;
my %user =
"fname" => "Foo",
"lname" => "Bar",
"email" => " foo@bar.com ",
;
for %user.kv -> $key, $value {
say "$key $value";
}
輸出:
fname Foo
lname Bar
email foo@bar.com
遍歷散列鍵
使用 "keys" 函數也可以遍歷散列鍵.
#!/usr/bin/env perl6
use v6;
my %phone =
"Foo" => 123,
"Bar" => 456,
;
for keys %phone -> $name {
say "$name %phone{$name}";
}
輸出:
Bar 456
Foo 123
POD文檔
#!/usr/bin/env perl6
use v6;
print "Hello";
=begin pod
=head1 Title
text
=end pod
say " World";
這會打印出Hello World
slurp
讀取整個文件內容到標量變量中
Perl 6 有一個內建模式來一次性吸入文件內容, 那就是把整個文件內容讀到一個標量變量中.
#!/usr/bin/env perl6
use v6;
my $filename = $*PROGRAM_NAME;
my $data = slurp $filename;
say $data.bytes;
Twigils 和特殊變量
Perl 6 有很多特殊變量.為了更容易地跟普通變量區分開,它們用一種叫做twigil的第二個前綴來標記。
通常,用戶自定義的變量有一個魔符($ @ 或%)在變量名前。
系統變量有額外的字符在魔符和變量名之間
Examples:
$*PROGRAM_NAME 包含當前運行的Perl 6 腳本的路徑.
$*CWD 是當前工作目錄的路徑。
$*IN 是標準輸入(STDIN).你可以使用 $*IN.get 讀入一行。
你可以閱讀S28了解更多。
比較操作符
有兩種相關的比較操作符. 一種是比較數字,一種是比較字符串,基于 ASCII表。
3 == 4 # false
'35' eq 35.0 # false
'35' == 35.0 # true
13 > 2 # true
13 gt 2 # false !!!
"hello" == "world" # throws exception
"hello" eq "world" # false
"hello" == "" # throws exception
"hello" eq "" # false
#!/usr/bin/env perl6
use v6;
say 4 == 4 ?? "TRUE" !! "FALSE"; # TRUE
say 3 == 4 ?? "TRUE" !! "FALSE"; # FALSE
say "3.0" == 3 ?? "TRUE" !! "FALSE"; # TRUE
say "3.0" eq 3 ?? "TRUE" !! "FALSE"; # FALSE
say 13 > 2 ?? "TRUE" !! "FALSE"; # TRUE
say 13 gt 2 ?? "TRUE" !! "FALSE"; # FALSE
say "foo" == "" ?? "TRUE" !! "FALSE"; # TRUE
say "foo" eq "" ?? "TRUE" !! "FALSE"; # FALSE
say "foo" == "bar" ?? "TRUE" !! "FALSE"; # TRUE
say "foo" eq "bar" ?? "TRUE" !! "FALSE"; # FALSE
不能轉換字符串為數字:十進制數字必須以合法數字或點開頭
布爾表達式
布爾表達式 (邏輯操作符)
if COND and COND {
}
if COND or COND {
}
if not COND {
}
examples/scalars/logical_operators.p6
#!/usr/bin/env perl6
use v6;
say (2 and 1); # 1
say (1 and 2); # 2
say (1 and 0); # 0
say (0 and 1); # 0
say (0 and 0); # 0
say "---";
say (1 or 0); # 1
say (1 or 2); # 1
say (0 or 1); # 1
say (0 or 0); # 0
say "---";
say (1 // 0); # 1
say (0 // 1); # 0
say (0 // 0); # 0
say "---";
say (1 xor 0); # 1
say (0 xor 1); # 1
say (0 xor 0); # 0
say (1 xor 1); # Nil
say "---";
say (not 1); # False
say (not 0); # True
say "---";
超級or - 多選分支
#!/usr/bin/env perl6
use v6;
say "Please select an option:";
say "1) one";
say "2) two";
say "3) three";
my $c = prompt('');
if $c == 1 or $c == 2 or $c == 3 {
say "correct choice: $c";
} else {
say "Incorrect choice: $c";
}
這種新穎的語法
if $c == 1|2|3 {
say "correct choice: $c";
} else {
say "Incorrect choice: $c";
}
從鍵盤讀入
prompt讀取用戶輸入內容知道用戶按下 Enter鍵。但是它只傳遞第一個換行之前的內容
#!/usr/bin/env perl6
use v6;
my $name = prompt("Please type in yourname: ");
say "Hello $name"; #還不能處理漢字,prompt是一個函數,其參數為提示信息
讀取文件內容到數組中
當我們把調用slurp() 的結果放進數組中時,數組中將只有一個元素,該元素的值就是要讀取的文件中的所有內容。如果你想讀取所有行到數組中不同的元素中,你需要使用 lines
函數。
#!/usr/bin/env perl6
use v6;
my $filename = $*PROGRAM_NAME;
# reads all the content of the file in the first element of the array!
my @content = slurp $filename;
say @content.elems;
# reads all the content of the file, every line an element in the array
my @rows = lines $filename.IO;
say @rows.elems;
求和
numbers.txt:(另存為ansi編碼)
3
8
19
-7
13
#!/usr/bin/env perl6
use v6;
my $filename = 'numbers.txt';
my $total;
my $count;
my $min;
my $max;
if (my $fh = open $filename, :r) {
for $fh.lines -> $line {
if (not $count) {
$min = $max = $line;
}
$total += $line;
if ($min > $line) {
$min = $line;
}
if ($max < $line) {
$max = $line;
}
$count++;
}
my $average = $total / $count;
say "Total: $total, Count: $count Average: $average Min: $min Max: $max";
} else {
say "Could not open '$filename'";
}
# There is a minor issue in this solution, what if there are no values at all in the file?
列表和數組
括號()中用逗號分隔的東西叫做列表。實際上你甚至不需要括號。 列表就是一組有序的標量值。例子:
#!/usr/bin/env perl6
use v6;
(1, 5.2, "apple"); # 3 values
(1,2,3,4,5,6,7,8,9,10); # 很好但是我們很懶,所以我們這樣寫::
(1..10); # 與(1,2,3,4,5,6,7,8,9,10)一樣
(1..Inf); # represents the list of all the numbers
(1..*); # this too
("apple", "banana", "peach", "blueberry"); # is the same as
<apple banana peach blueberry>; # quote word
my ($x, $y, $z); # 我們也能使用標量變量作為列表的元素
在大多數情況下,我們實際上甚至不需要括號.
列表賦值
my ($x, $y, $z);
($x, $y, $z) = f(); # 如果 f() 返回 (2, 3, 7) 則它幾乎與$x=2; $y=3; $z=7;相同
($x, $y, $z) = f(); # 如果 f() 返回 (2, 3, 7, 9), 則忽略 9
($x, $y, $z) = f(); # 如果 f() 返回 (2, 3); 則 $z 是 undef
我們怎么交換兩個變量的值,比如說 $x 和 $y?
交換兩個值
#!/usr/bin/env perl6
use v6;
say "Type in two values:";
my $a = $*IN.get;
my $b = $*IN.get;
($a, $b) = ($b, $a);
say $a;
say $b;
用for循環遍歷列表的元素
#!/usr/bin/env perl6
use v6;
for "Foo", "Bar", "Baz" -> $name {
say $name;
}
say "---";
for 1..5 -> $i {
say $i;
}
say "---";
for 1..Inf -> $i {
say $i;
last if $i > 3;
}
say "---";
for 1..* -> $i {
say $i;
last if $i > 3;
}
創建數組, 遍歷數組
你可以給一列值賦值給數組。
在雙引號中數組不會進行插值。這與Perl 5 不一樣。
就像你看見的,列表周圍的括號是可選的。
#!/usr/bin/env perl6
use v6;
my @colors = "Blue", "Yellow", "Brown", "White"; # 列表周圍的括號是可選的
say @colors;
say "--------------------------------"; # just for separation...
say "@colors"; # 沒有插值!
say "--------------------------------"; # just for separation...
say "{@colors}";
say "--------------------------------"; # just for separation...
say "@colors[]";
say "--------------------------------"; # just for separation...
for @colors -> $color {
say $color;
}
Output:
Blue Yellow Brown White
--------------------------------
Blue Yellow Brown White
--------------------------------
Blue
Yellow
Brown
White
數組元素 (create menu)
#!/usr/bin/env perl6
use v6;
my @colors = <Blue Yellow Brown White>;
for 1..@colors.elems -> $i {
say "$i) @colors[$i-1]";
}
my $input = prompt("Please select a number: ");
say "You selected @colors[$input-1]";
數組賦值
#!/usr/bin/env perl6
use v6;
my $owner = "Moose";
my @tenants = "Foo", "Bar";
my @people = ($owner, 'Baz', @tenants); # 數組被展開:
say "{@people}"; # Moose Baz Foo Bar
my ($x, @y) = (1, 2, 3, 4);
say $x; # $x = 1
say "{@y}"; # @y = (2, 3, 4)
命令行選項
@*ARGS 數組由語言維護,它存儲著命令行的值。
#!/usr/bin/env perl6
use v6;
my $color = @*ARGS[0];
if not $color {
my @colors = <Blue Yellow Brown White>;
for 1 .. @colors.elems -> $i {
say "$i) @colors[$i-1]";
}
my $input = prompt "Please select a number: ";
$color = @colors[$input-1];
}
say "You selected $color";
處理 CSV 文件
examples/arrays/sample_csv_file.csv
Foo,Bar,10,home
Orgo,Morgo,7,away
Big,Shrek,100,US
Small,Fiona,9,tower
examples/arrays/process_csv_file.p6
#!/usr/bin/env perl6
use v6;
my $file = 'examples/arrays/sample_csv_file.csv';
if defined @*ARGS[0] {
$file = @*ARGS[0];
}
my $sum = 0;
my $data = open $file;
for $data.lines -> $line {
my @columns = split ",", $line;
$sum += @columns[2];
}
say $sum;
join
examples/arrays/join.p6
#!/usr/bin/env perl6
use v6;
my @fields = <Foo Bar foo@bar.com>;
my $line = join ";", @fields;
say $line; # Foo;Bar;foo@bar.com
uniq 函數
examples/arrays/unique.p6
#!/usr/bin/env perl6
use v6;
my @duplicates = 1, 1, 2, 5, 1, 4, 3, 2, 1;
say @duplicates.perl;
# prints Array.new(1, 1, 2, 5, 1, 4, 3, 2, 1)
my @unique = uniq @duplicates;
say @unique.perl;
# prints Array.new(1, 2, 5, 4, 3)
my @chars = <b c a d b a a a b>;
say @chars.perl;
# prints Array.new("b", "c", "a", "d", "b", "a", "a", "a", "b")
my @singles = uniq @chars;
say @singles.perl;
# prints Array.new("b", "c", "a", "d")
examples/arrays/loop_over_array.p6
#!/usr/bin/env perl6
use v6;
my @fellows = <Foo Bar Baz>;
for @fellows -> $name {
say $name;
}
examples/arrays/looping_over_many_elements.p6
#!/usr/bin/env perl6
use v6;
my @scores = <
Valencia 1 1 Recreativo_Huelva
Athletic_Bilbao 2 5 Real_Madrid
Malaga 2 2 Sevilla_FC
Sporting_Gijon 3 2 Deportivo_La_Coruna
Valladolid 1 0 Getafe
Real_Betis 0 0 Osasuna
Racing_Santander 5 0 Numancia
Espanyol 3 3 Mallorca
Atletico_Madrid 3 2 Villarreal
Almeria 0 2 Barcelona
>;
for @scores -> $home, $home_score, $guest_score, $guest {
say "$home $guest $home_score : $guest_score";
}
缺失值
examples/arrays/missing_values.p6
#!/usr/bin/env perl6
use v6;
for (1, 2, 3, 4, 5) -> $x, $y {
say "$x $y";
}
say 'done';
examples/arrays/missing_values.p6.output
1 2
3 4
Not enough positional parameters passed; got 1 but expected 2
in block <anon> at examples/arrays/missing_values.p6:4
examples/arrays/missing_values_fixed.p6
#!/usr/bin/env perl6
use v6;
for (1, 2, 3, 4, 5) -> $x, $y? {
say "$x $y";
}
say 'done';
examples/arrays/missing_values_fixed.p6.output
1 2
3 4
use of uninitialized value of type Mu in string context
in block <anon> at examples/arrays/missing_values_fixed.p6:5
5
done
examples/arrays/z.p6
#!/usr/bin/env perl6
use v6;
my @chars = <a b c>;
my @numbers = <1 2 3>;
for @chars Z @numbers -> $letter, $number {
say "$letter $number";
}
Output:
examples/arrays/z.p6.out
a 1
b 2
c 3
examples/arrays/z_on_more.p6
#!/usr/bin/env perl6
use v6;
my @operator = <+ - *>;
my @left = <1 2 3>;
my @right = <7 8 9>;
for @left Z @operator Z @right -> $a, $o, $b {
say "$a $o $b";
}
Output:
examples/arrays/z_on_more.p6.out
1 + 7
2 - 8
3 * 9
xx - string multiplicator
examples/arrays/xx.p6
#!/usr/bin/env perl6
use v6;
my @moose = "moose" xx 3;
say "{@moose}";
sort values
examples/arrays/sort.p6
#!/usr/bin/env perl6
use v6;
my @names = <foo bar moose bu>;
my @sorted_names = sort @names;
say @sorted_names.perl; # ["bar", "bu", "foo", "moose"]
my @numbers = 23, 17, 4;
my @sorted_numbers = sort @numbers;
say @sorted_numbers.perl; # [4, 17, 23]
my @sort_names_by_length = sort { $^a.bytes <=> $^b.bytes }, @names;
say @sort_names_by_length.perl; # ["bu", "bar", "foo", "moose"]
# the same result with one sub (Schwartizian transformation)
my @sort_1 = sort { $_.bytes }, @names;
say @sort_1.perl; # ["bu", "bar", "foo", "moose"]
my @sort_2 = @names.sort({ $_.bytes });
say @sort_2.perl; # ["bu", "bar", "foo", "moose"]
my @sort_3 = @names.sort: { $_.bytes };
say @sort_3.perl; # ["bu", "bar", "foo", "moose"]
my @words = <moo foo bar moose bu>;
say @words.sort({ $^a.bytes <=> $^b.bytes}).perl; # ["bu", "moo", "foo", "bar", "moose"];
say @words.sort({ $^a.bytes <=> $^b.bytes or $^a cmp $^b}).perl; # ["bu", "bar", "foo", "moo", "moose"];
# TODO: should be also:
# say @words.sort({ $^a.bytes <=> $^b.bytes }, {$^a cmp $^b}).perl; # ["bu", "bar", "foo", "moo", "moose"];
# say @words.sort({ $_.bytes }, {$^a cmp $^b}).perl; # ["bu", "bar", "foo", "moo", "moose"];
創建數組, Data::Dumper, 調試打印
在Perl6 中創建數組跟在Perl5 中一樣,對于調試打印我們會使用Perl6 的.perl
方法來代替Perl5中的Data::Dumper
.
use v6;
my @numbers = ("one", "two", "three");
say @numbers.perl; # Array.new("one", "two", "three")
在Perl6中,列表周圍的圓括號不再需要了
:
use v6;
my @digits = 1, 3, 6;
say @digits.perl; # Array.new(1, 3, 6)
qw() 不再使用
Perl 5 中的 qw()
操作符被尖括號
取代:
use v6;
my @names = <foo bar baz> ;
say @names.perl; # Array.new("foo", "bar", "baz")
字符串中的數組插值
在雙引號字符串中,數組不再插值:
use v6;
my @names = "red","yellow","green";
say "@names"; # @names
你可以放心地寫下這樣的句子而不轉義 @ 符號:
use v6;
my @names = <Tom Cat>;
say "joe@names.org"; # joe@names.org
如果你確實要內插數組的值,你必須將數組放在一對 花括號
中:
use v6;
my @names = < foo bar baz > ;
say "names: {@names}"; # names: foo bar baz
取數組元素, 魔符不變
當在Perl 6 中訪問數組的元素時,元素前的符號不會改變!這對Perl 5 程序員來說會很奇怪,但是長期看來它有優勢。
use v6;
my @names = < foo bar baz > ;
say @names[0]; # foo
內插一個數組元素
作為一個特殊情況,一個數組元素能被內插在雙引號字符串中而不使用花括號。術語 post-circumfix
對于方括號
或花括號
來說是一個一般稱謂. 一般地,帶有前置符號的變量可以被內插.
use v6;
my @names = < foo bar baz >;
say "name:@names[0]"; # name: foo
數組中元素的個數
在 Perl 6 中,推薦使用elems()
方法和相關的函數來得到數組的元素個數。實際上,我認為面向對象的寫法更美觀:
use v6;
my @names = < foo bar baz >;
say elems @names; # 3
say @names.elems; # 3
范圍
范圍在Perl 6 中跟Perl 5 很像:
use v6;
my @d = 1..11;
say @d.perl; # Array.new(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
The same works with scalar variables on either side:
use v6;
my $start = 1;
my $end = 11;
my @d = $start .. $end;
say @d.perl; # Array.new(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
ranges一個很有意思的方面可能是,你能對單個或兩個范圍的終點使用^
符號告訴它們排除終點:
use v6;
my $start = 1;
my $end = 11;
my @d = $start ^..^ $end; # 1的終點是1,,11的終點是11,排除這兩個值
say @d.perl; # Array.new(2, 3, 4, 5, 6, 7, 8, 9, 10)
范圍操作符同樣對字符
有效:
use v6;
my @chars = ('a' .. 'd');
say @chars.perl; # Array.new("a", "b", "c", "d")
for 和 foreach 循環
Perl 5 中C風格的for 循環現在叫做loop,但是我不會在這兒展示它。
use v6;
for 1..3 -> $i {
say $i;
}
輸出為
1
2
3
這同樣對數組有效:
use v6;
my @names = < foo bar baz >;
for @names -> $n {
say $n;
}
輸出:
foo
bar
baz
順便提一下,這是你不用使用my聲明一個變量
的情況之一。循環變量自動被聲明好了,并且作用到for循環塊中。
遍歷數組的索引
如果你想遍歷數組的索引,你可以使用范圍,從0一直到最大的索引值。最大索引值比數組元素的個數少1.你可以用 @names.elems -1
作為最優的范圍 ,或者你可以使用 ^
符號告訴范圍排除最后一個值:
use v6;
my @names = < foo bar baz >;
for 0 ..^@names.elems -> $i {
say "$i {@names[$i]}";
}
輸出:
0 foo
1 bar
2 baz
或者這樣:
use v6;
my @names = < foo bar baz >;
for @names.keys -> $i {
say "$i {@names[$i]}";
}
從散列中借來的keys()
方法會返回數組所有的索引。即使你的數組含有‘空’值,即帶有undef
的元素,keys()
仍舊會包含這樣的元素的索引。
split
split() 表現的就像Perl 5 中split的副本
一樣,但是默認行為不再應用,無論如何,你應該查看文檔:
use v6;
say "a,b,c".split(',').perl; # ("a", "b", "c").list
三元操作符
use v6;
my $age = 42;
if $age > 18 {
say "Above 18";
} else {
say "Below 18";
}
say $age > 18 ?? "Above 18" !! "Below 18";
語法: COND ?? VALUE_IF_TRUE !! VALUE_IF_FALSE
數字運算符
數字運算符可以用在標量值上面。
examples/scalars/numerical_operators.p6
#!/usr/bin/env perl6
use v6;
my $x = 3;
my $y = 11;
my $z = $x + $y;
say $z; # 14
$z = $x * $y;
say $z; # 33
say $y / $x; # 3.66666666666667
$z = $y % $x; # (模)
say $z; # 2
$z += 14; # is the same as $z = $z + 14;
say $z; # 16
$z++; # is the same as $z = $z + 1;
$z--; # is the same as $z = $z - 1;
$z = 23 ** 2; # 冪
say $z; # 529
文件讀取
從文件中讀取行
打開文件時的模式:
:r - read
:w - write
:a - append
open函數的兩個參數:文件名和模式.為了打開一個文件讀取,模式需為 :r . 此函數要么返回一個存在標量變量中的文件句柄,要么失敗時返回 undef 。
$fh = open $filename, :r
一旦我們打開了一個文件句柄,我們可以使用 get 方法 ($fh.get) 從給定的文件中讀取一行。
你也可以連續調用 get 方法 讀取多行,但還有更好的方法。
examples/files/read_one_line.p6
#!/usr/bin/env perl6
use v6;
my $filename = $*PROGRAM_NAME;
my $fh = open $filename;
my $line = $fh.get;
say $line;
讀取所有行
#!/usr/bin/env perl6
use v6;
my $filename = $*PROGRAM_NAME;
my $fh = open $filename;
while (defined my $line = $fh.get) {
say $line;
}
逐行讀取文件
#!/usr/bin/env perl6
use v6;
my $filename = $*PROGRAM_NAME;
my $fh = open $filename;
for $fh.lines -> $line {
say $line;
}
lines 方法返回文件的所有行或部分行
在Perl 6中對存在的數據結構進行操作是有趣的,但是如果沒有輸入與輸出的話,就會限制在真實世界中的用途。
因此,讀取文件內容是一個明智的操作.
open
get
read
IO
lines
一行行讀取(Read line-by-line)
open 函數會打開一個文件,默認情況下,你可以顯示地傳遞一個 :r 作為open函數的第二個參數。 Open會返回一個文件句柄,即一個IO類的實例。
get 方法會從文件讀取并返回一行,末尾的新行會自動被移除。 (Perl 5 開發者也可以認為 get 方法自動調用了chomp操作.)
my $fh = open $filename;
my $line = $fh.get;
你也可以在一個while循環中讀取文件的所有行。 與 Perl 5相反, 在這個while循環中,對是否定義沒有隱式地檢測.你必須在條件語句中顯示地添加單詞defined.否則,讀取操作將在第一個空行處停止。
my $fh = open $filename;
while (defined my $line = $fh.get)
{
say $line;
}
在for循環中使用 lines
方法可能更具有Perl-6風格。 lines 方法會依次讀取文件的每一行,然后將讀取到行賦值給變量 $line
,然后執行代碼塊。
my $fh = open $filename;
for $fh.lines -> $line {
say $line;
}
寫文件
為了寫入內容到文件我們首先要開啟 :w 模式.如果成功,我們得到一個文件句柄,在該文件句柄上我們可以使用普通的諸如print()、say()、或printf()等輸出方法。
examples/files/write_file.p6
#!/usr/bin/env perl6
use v6;
my $filename = "temp.txt";
my $fh = open $filename, :w;
$fh.say("hello world");
$fh.close;
元操作符
元操作符
examples/arrays/assignment_shortcut.p6
#!/usr/bin/env perl6
use v6;
my $num = 23;
say $num + 19; # 42
say $num; # 23
$num += 19;
say $num; # 42
賦值時的方法調用
在Perl 6 中它擴展了點操作符的功能,允許在對象上進行方法調用。想想下面的例子。subst方法能夠用一個字符串替換另外一個,但是并不改變原來的字符串。默認地,它返回改變了的字符串.
如果你想改變原字符串,你可以寫為 $str = $str.subst('B', 'X');
或者你可以寫成它的 shortcut version.
examples/arrays/assignment_operators.p6
#!/usr/bin/env perl6
use v6;
my $str = 'ABBA';
say $str.subst('B', 'X'); # AXBA
say $str; # ABBA
say $str .= subst('B', 'X'); # AXBA
say $str; # AXBA
賦值時調用函數
這也同樣可以用于函數中,就如 $lower = min($lower, $new_value);
你可以寫為 $lower min= $new_value;
examples/arrays/assignment_function_shortcuts.p6
#!/usr/bin/env perl6
use v6;
my $lower = 2;
$lower min= 3;
say $lower; # 2
$lower min= 1;
say $lower; # 1
這甚至可以有效地使用逗號操作符向數組中壓入更多值。
my @a = (1, 2, 3);
@a ,= 4;
@a.say;
反轉關系操作符
等號(==)操作符在Perl6 中用于比較數字,eq用于比較字符串。 The negated version are the same just with an exclamation mark ( ! ) in front of them. 所以它們看起來就是 !== 和 !eq.
幸運的是,那些都有它們的快捷寫法,可以寫為!=和ne。
其他操作符也有相應的反轉版本,所以你可以寫 !>= ,它的意思是不大于 (對于數字) 并且你可以寫!gt ,對于字符串來說是一樣的. 我沒有全部攤出我們為什么需要這個。
一個我能明白的優點是如果你創建了一個叫做I的操作符,然后你會自動得到一個看起來像!I 的操作符,那是它的反轉。
examples/arrays/negated_operators.p6
#!/usr/bin/env perl6
use v6;
# 相等
say 1 == 1 ?? 'y' !! 'n'; # y
say 1 !== 1 ?? 'y' !! 'n'; # n
say 1 != 1 ?? 'y' !! 'n'; # n
say 'ac' eq 'dc' ?? 'y' !! 'n'; # n
say 'ac' !eq 'dc' ?? 'y' !! 'n'; # y
say 1 < 2 ?? 'y' !! 'n'; # y
####say 1 !< 2 ?? 'y' !! 'n'; # n
say 1 <= 2 ?? 'y' !! 'n'; # y
####say 1 !<= 2 ?? 'y' !! 'n'; # n
say 1 >= 2 ?? 'y' !! 'n'; # n
####say 1 !>= 2 ?? 'y' !! 'n'; # y
反轉操作符
反轉操作符會反轉兩個操作數的意思. 所以就像交換 $b cmp $a
中參數的值,你可以寫為 $a Rcmp $b
.
examples/arrays/reversed_operators.p6
#!/usr/bin/env perl6
use v6;
# 宇宙飛船操作符
say 1 <=> 2; # -1
say 2 <=> 1; # 1
say 1 R<=> 2; # 1
say 2 R<=> 1; # -1
輸出:
examples/arrays/reversed_operators.p6.out
Increase
Decrease
Decrease
Increase
Hyper 操作符
examples/arrays/hyper.p6
#!/usr/bin/env perl6
use v6;
my @x = (1, 2) >>+<< (3, 4);
say @x.perl; # [4, 6]
#my @d = (1, 2) >>+<< (3);
#say @d.perl; # [4, 6]
# Non-dwimmy hyperoperator cannot be used on arrays of different sizes or dimensions.
my @z = (1, 2, 3, 4) >>+>> (1, 2);
say @z.perl; # [2, 4, 5, 6]
@z = (1, 2, 3, 4) <<+>> (1, 2);
say @z.perl; # [2, 4, 5, 6]
@z = (4) <<+>> (1, 2);
say @z.perl; # [5, 6]
my @y = (1, 2) >>+>> 1;
say @y.perl; # [2, 3]
examples/arrays/hyper.p6.out
Array.new(4, 6)
Array.new(2, 4, 4, 6)
Array.new(2, 4, 4, 6)
Array.new(5, 6)
Array.new(2, 3)
Reduction 操作符
examples/arrays/reduction_operators.p6
#!/usr/bin/env perl6
use v6;
say [+] 1, 2; # 3
say [+] 1..10; # 55
# 階乘
say [*] 1..5; # 120
say [**] 2,2,2; # 16 == 2**2**2
my @numbers = (2, 4, 3);
# 檢查數字是否是遞增順序
say [<] @numbers; # False
say [<] sort @numbers; # True
輸出
examples/arrays/reduction_operators.p6.out
3
55
120
16
False
True
Reduction Triangle operators
The ~ in front of the operator is only needed for the stringification of the list to inject spaces between the values when printed.
examples/arrays/triangle_operators.p6
#!/usr/bin/env perl6
use v6;
say ~[\+] 1..5; # 1 3 6 10 15 (1 1+2 1+2+3 ... 1+2+3+4+5)
say ~[\*] 1..5; # 1 2 6 24 120
輸出:
examples/arrays/triangle_operators.p6.out
1 3 6 10 15
1 2 6 24 120
交叉操作符 Cross operators
examples/arrays/cross_operators.p6
#!/usr/bin/env perl6
use v6;
my @x = (1, 2) X+ (4, 7);
say @x.perl; # [5, 8, 6, 9] 1+4,1+7,2+4,2+7
my @y = 1, 2 X+ 4, 7;
say @y.perl; # [5, 8, 6, 9]
my @str = 1, 2 X~ 4, 7;
say @str.perl; # ["14", "17", "24", "27"]
# without any special operator (is the same with X, should be)
my @z = 1, 2 X 4, 7;
say @z.perl; # [1, 4, 1, 7, 2, 4, 2, 7]
輸出:
examples/arrays/cross_operators.p6.out
Array.new(5, 8, 6, 9)
Array.new(5, 8, 6, 9)
Array.new("14", "17", "24", "27")
Array.new(1, 4, 1, 7, 2, 4, 2, 7)
積的交叉
my @y = 1, 2 X* 4, 7;
輸出 4 7 8 14
字符串操作
自動將字符串轉換為數字
examples/scalars/add.p6
#!/usr/bin/env perl6
use v6;
my $a = prompt "First number:";
my $b = prompt "Second number:";
my $c = $a + $b;
say "\nResult: $c";
字符串操作
examples/scalars/string_operators.p6
#!/usr/bin/env perl6
use v6;
my $x = "Hello";
my $y = "World";
# ~ 是連接操作符,連接字符串
my $z = $x ~ " " ~ $y; # the same as "$x $y"
say $z; # Hello World
my $w = "Take " ~ (2 + 3);
say $w; # Take 5
say "Take 2 + 3"; # Take 2 + 3
say "Take {2 + 3}"; # Take 5
$z ~= "! "; # the same as $z = $z ~ "! ";
say "'$z'"; # 'Hello World! '
~ 連接2個字符串.
就像上面見到的那樣,任何操作符都能使用花括號語法插入到字符串中。.
字符串連接
examples/scalars/concat.p6
#!/usr/bin/env perl6
use v6;
my $a = prompt "First string:";
my $b = prompt "Second string:";
my $c = $a ~ $b;
say "\nResult: $c";
字符串重復操作
examples/scalars/string_repetition.p6
#!/usr/bin/env perl6
use v6;
my $z = "Hello World! ";
# x is the string repetition operator
my $q = $z x 3;
say " ' $q ' "; # 'Hello World! Hello World! Hello World! '
字符串函數 - index
#!/usr/bin/env perl6
use v6;
my $s = "The black cat jumped from the green tree";
say index $s, "e"; # 2
say index $s, "e", 3; # 18
say rindex $s, "e"; # 39
say rindex $s, "e", 38; # 38
say rindex $s, "e", 37; # 33
字符串函數 - substr
字符串函數: substr
examples/scalars/string_functions_substr.p6
#!/usr/bin/env perl6
use v6;
my $s = "The black cat climbed the green tree";
my $z;
$z = substr $s, 4, 5; # $z = black
say $z;
$z = substr $s, 4, *-11; # $z = black cat climbed the 從索引4開始截取,不要最后的11個字符
say $z;
$z = substr $s, 14; # $z = climbed the green tree,從索引14開始知道結束
say $z;
$z = substr $s, *-4; # $z = tree
say $z;
$z = substr $s, *-4, 2; # $z = tr
say $z;
值在給定的列表中嗎
怎樣找出一個給定的值是否在一些值的中間?這跟SQL中的IN操作符相似。
在 Perl 6 中,有一個 any() 函數,其功能與SQL 中的IN 關鍵字相似。讓我們看看它如何工作:
它是一個weekday嗎?
use v6;
my @weekdays = <Monday Sunday Tuesday Wednesday Thursday Friday Saturday >;
my $day = "Tuesday";
say $day eq any(@weekdays)
??
"$day is a weekday"
!!
"$day is NOT a weekday";
上面的代碼將打印出:
Tuesday is a weekday
perl會嘗試使用 eq 讓@weekdays中的每一個元素都與$day標量的內容相比較,如果它們中的任意一個為真,表達式即為真。
Perl 6 中的三元操作符
旁注: ?? !! 對Perl 6 的三元操作符。它語法如下:
CONDITION
??
VALUE_IF_TRUE
!!
VALUE_IF_FALSE
;
它仍然是weekday嗎?
更完整的例子讓我們來看當所有這些值都不匹配時會發生什么:
use v6;
my @weekdays = <Monday Sunday Tuesday Wednesday Thursday Friday Saturday >;
my $other = "Holiday";
say $other eq any(@weekdays)
??
"$other is a weekday"
!!
"$other is NOT a weekday";
代碼相同但是不會打印匹配值:
Holiday is NOT a weekday
使用小于號比較數字
下個例子我們將會看到any函數能用于其它諸如小于號操作符的比較運算符上:
use v6;
my @numbers = (6, -12, 20);
say any(@numbers)< 0
?? "There is a negative number"
!! "No negative number here";
結果為:
There is a negative number
你也可以使用其它操作符.
假使沒有負數它也有效:
use v6;
my @positive_numbers = (6, 12, 20);
say any(@positive_numbers) < 0
?? "There is a negative number"
!! "No negative number here";
輸出:
No negative number here
其它關鍵字: none
, all
, one
還有其它函數, 不僅僅是 any 函數: (all, one and none)
use v6;
my @positive_numbers = (6, 12, 20);
say none(@positive_numbers) < 0
?? "No negative number here"
!! "There is a negative number";
會打印:
No negative number here
use v6;
my @positive_numbers = (6, 12, 20);
say all(@positive_numbers) > 0
?? "All are positive numbers"
!! "There is a NOT positive number";
會打印:
All are positive numbers
使用最合適的那個函數。
更短的寫法
有時候你有一個值,你需要檢測它是否等于一個所列值中的任意一個:
use v6;
my $n = 12;
say ($n == 23 or $n == 42) ?? "ok" !! "not ok"; # not ok
使用 any 函數你可以這樣寫:
use v6;
my $n = 12;
say $n == any(23, 42)
?? "ok"
!! "not ok"; # not ok
any 函數也有一個單管道線的中綴操作符版本,所以你也能這樣寫:
use v6;
my $n = 12;
say $n == 23|42
?? "ok"
!! "not ok"; # not ok
交叉
這些關鍵詞和相關操作所做的實際上是創建了一種叫做Junction
的數據類型。它是一個標量,以一種無序的方式存儲著多個值。跟集合類似。
第一個例子也可以這樣寫:
use v6;
my $weekdays = any <Monday Sunday Tuesday Wednesday Thursday Friday Saturday >;
my $day = "Tuesday";
say $day eq $weekdays
?? "$day is a weekday"
!! "$day is NOT a weekday";
這里我們創建了一個junction而非數組,然后使用該junction進行比較。
Other operations on Junctions
In addition to the comparison operations we saw earlier, we can do other operations on junctions. The operation will be executed on each one of the values in the junction and the result will be a new junction with the changed values:
use v6;
my $numbers = any(23, 42);
$numbers.perl.say;
$numbers++;
$numbers.perl.say;
這會打印該 junction的perl表現:
any(23, 42)
any(24, 43)
Functions on Junctions
你也可以將 junctions 作為參數傳遞給函數。 The function will be executed on each value separately in an undefined order, and the result will be another junction. For example if we would like to create the 3 character version of the months we can use the following code:
use v6;
my $months = any ;
my $short_names = substr($months, 0, 3);
$short_names.perl.say;
Which should print
any("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
Perl 6 的正則
正則操作符
在 Perl 6 中智能匹配 ~~ 操作符用于正則匹配。
對于相反的匹配,使用 !~~ 操作符。
基本用法
use v6;
my $str = 'abc123';
if $str ~~ m/a/ {
say "Matching";
}
if $str !~~ m/z/ {
say "No z in $str";
}
兩個條件都是真的,所以兩組字符串 "Matching" 和"No z in abc123"都會被打印。
特殊符號
Perl6中有一個重要改變,那就是在Perl6 中,任何非字母數字字符
需要被轉義。
在下個例子中,我們需要轉義 -
符號:
use v6;
my $str = 'abc - 123';
if $str ~~ m/-/ {
say "Matching";
}
生成:
===SORRY!===
Unrecognized regex metacharacter - (must be quoted to match literally) at line 6, near "/) {\n s"
use v6;
my $str = 'abc - 123';
if $str ~~ m/\-/ {
say "Matching";
}
有效,打印匹配。
新特殊字符
#
現在是一個特殊字符,代表注釋,所以當我們真正需要一個#
號時,需要轉義:
use v6;
my $str = 'abc # 123';
if $str ~~ m/(#.)/ {
say "match '$/'";
}
報錯:
===SORRY!===
Unrecognized regex metacharacter ( (must be quoted to match literally) at line 6, near "#.)/ {\n "
轉義后正確:
use v6;
my $str = 'abc # 123';
if $str ~~ m/(\#.)/ {
say "match '$/'";
}
Perl 6 的匹配變量
每次一有正則操作,一個叫做 $/
的本地化變量被設置成實際匹配到的值。
use v6;
my $str = 'abc123';
if $str ~~ m/a/ {
say "Matching '$/'"; # Matching 'a'
}
if $str !~~ m/z/ {
say "No z in $str '$/'"; # No z in abc123 ''
}
Perl 6 正則中的空格
在Perl 6 中,正則默認忽略空格。
use v6;
my $str = 'The black cat climbed to the green tree.';
if $str ~~ m/black/ {
say "Matching '$/'"; # Matching 'black'
}
if $str ~~ m/black cat/ {
say "Matching '$/'";
} else {
say "No match as whitespaces are disregarded"; # prints this
}
那怎樣匹配空格呢?
use v6;
my $str = 'The black cat climbed to the green tree.';
if $str ~~ m/black\scat/ {
say "Matching '$/' - Perl 5 style white-space meta character works";
}
if $str ~~ m/black \s cat/ {
say "Matching '$/' - Meta white-space matched, real space is disregarded";
}
if $str ~~ m/black ' ' cat/ {
print "Matching '$/' - ";
say "the real Perl 6 style would be to use strings embedded in regexes";
}
if $str ~~ m/black cat/ {
print "Matching '$/' - ";
say "or maybe the Perl 6 style is using named character classes ";
}
任何情況下,我們可以這樣寫:
use v6;
my $str = 'The black cat climbed to the green tree.';
if $str ~~ m/ b l a c k c a t/ {
say "Matching '$/' - a regex in Perl 6 is just a sequence of tokens";
}
你看,你可以使用單引號
在正則中嵌入字面字符串,也有新類型的字符類,使用尖括號。
匹配任何字符
點(.)匹配任何字符,包括換行符
。
如果你想匹配除新行外的所有其他字符,你可以使用 \N
特殊字符類。
use v6;
my $str = 'The black cat climbed to the green tree.';
if $str ~~ m/c./ {
say "Matching '$/'"; # 'ck'
}
my $text = "
The black cat
climbed the green tree";
if $text ~~ m/t./ {
say "Matching '$/'";
}
第一個正則匹配并打印'ck',第二個打印:
't
'
使用 \N
:
use v6;
my $text = "
The black cat
climbed the green tree";
if $text ~~ m/t\N/ {
say "Matching '$/'"; # 'th' of the word 'the'
}
在最后一個例子中你看到 \N
能匹配字母 h,而非新行。
Perl6的一些特性
> my $foo = "bar";
bar
> if $foo eq "foo" | "bar" | "baz" { say "ok" }
ok
> my $num = 10;
10
> if 5 < $num < 15 { say "ok" }
ok
> say 1, 2, 4 ... 1024
1 2 4 8 16 32 64 128 256 512 1024
> my @fib = 1, 1, *+* ... *;
1 1 2 3 ...
> say @fib[0..9]
1 1 2 3 5 8 13 21 34 55
> say @fib[^10]
1 1 2 3 5 8 13 21 34 55
> say [+] 1..100
5050
> say 1..6 Z~ 'A'..'F'
1A 2B 3C 4D 5E 6F
> say 1..3 X~ 'A'..'D'
1A 1B 1C 1D 2A 2B 2C 2D 3A 3B 3C 3D
Perl 6 中一系列整數的操作
Perl 6 中一系列整數的操作
my $x = 23;
my $z = 27;
for $x .. $z -> $i {
say $i;
}
會打印出期望的數字 23, 24, 25, 26, 27 .
C風格的循環
C風格, 有3部分的for循環在Perl 6 中也是可行的但不推薦。
my $x = 23;
my $z = 27;
loop (my $i = $x; $i <= $z; $i++) {
say $i;
}
序列
在Perl 6 中用 for 循環每隔2個數遍歷也是可以的,我們使用3個 . 而非2個 . 這里我們談論的是序列而非范圍。
我們設置序列的前兩個元素和序列的上限.
my $x = 23;
my $z = 27;
for $x, $x+2 ... $z -> $i {
say $i;
}
這會打印 23, 25, 27
你必須保證上限的準確:
for 1, 3 ... 7 -> $i {
say $i;
}
這會打印 1, 3, 5, 7
另一方面,這樣:
for 1, 3 ... 8 -> $i {
say $i;
}
會報錯。(現在已修正, 打印 1,3,5,7)
Perl 6 中的標量、數組、散列如何插值
標量、數組和散列插值
將標量放在雙引號中會進行插值,就跟Perl 5 中一樣:
use v6;
my $name = "Foo";
say "Hello $name, how are you?";
這會打印:
Hello Foo, how are you?
數組和散列不是這樣進行插值的,在字符串中,任何放進花括號
中的東西都會被插值,所以如果你有一個數組,您能這樣寫:
use v6;
my @names = <Foo Bar Moo>;
say "Hello {@names}, how are you?";
to get this output:
Hello Foo Bar Moo, how are you?
這里的問題是基于輸出結果你不知道數組是有3個元素還是2個:
"Foo Bar" 和 "Moo", 或僅僅一個元素: "Foo Bar Moo".
內插表達式
上面的就不是個問題! 在用雙引號引起來的字符串中,你可以將任何表達式放在花括號
中。表達式會被計算,其結果會被插值:
你可以這樣寫:
use v6;
my @names = <Foo Bar Moo>;
say "Hello { join(', ', @names) } how are you?";
輸出如下:
Hello Foo, Bar, Moo how are you?
然而這依然沒有準確地顯示有幾個值,這顯得稍微復雜了。
作為旁注,萬一你更喜歡面向對象的代碼,你也可以像下面這樣寫:
say "Hello { @names.join(', ') } how are you?";
結果一樣.
調試打印
對于基本的調試目的,做好使用數組的 .perl
方法:
say "Names: { @names.perl }";
那會打印:
Names: Array.new("Foo", "Bar", "Moo")
假使你想同時看到變量名呢?那你可以依賴數組在雙引號字符串中不插值這點這樣寫:
say " @names = { @names.perl }";
那會打印:
@names = Array.new("Foo", "Bar", "Moo")
僅僅是表達式
use v6;
say "Take 1+4";
會打印:
Take 1+4
就像我所寫的,你可以將任何表達式放進花括號中,你也可以這樣寫:
use v6;
say "Take {1+4}";
那會打印:
Take 5
插值散列
use v6;
my %phone = (
foo => 1,
bar => 2,
);
say "%phone = { %phone } ";
會打印:
%phone = foo 1 bar 2
這分不清哪些是鍵,哪些是值. 對于調試目的,你最好用 .perl
方法:
say "%phone = { %phone.perl } ";
會打印:
%phone = ("foo" => 1, "bar" => 2).hash
插值多維數組
use v6;
my @matrix = (
[1, 2],
[3, 4],
);
say "@matrix = { @matrix.perl }";
輸出:
@matrix = Array.new([1, 2], [3, 4])