翻譯自 perl6maven.com
exit陨闹,warn未斑,die
exit
#!/usr/bin/env perl6
use v6;
say "hello";
exit;
say "world"; # 這句不會執(zhí)行了
#!/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
使用關(guān)鍵字 say打印出字符串看蚜,并在字符串結(jié)尾自動添加一個換行符检诗。字符串被雙引號包裹住酝枢。Perl 6 中語句以分號結(jié)束恬偷。
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 腳本竣付。有些人只是使用常規(guī)的pl后綴诡延,而實際上在UNIX 系統(tǒng)中這沒有什么不可。只是在有些編輯器是基于它們的文件后綴名來高亮語法時才顯得必要卑笨。
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 來運行的話,會發(fā)生什么桶良?
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.
現(xiàn)在問題更清晰了 (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 結(jié)構(gòu)
#!/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"; }
}
標量變量
字符串可以存儲在所謂的標量變量中座舍。每個標量變量以符號 $ 開頭,后面跟著字母數(shù)字陨帆、單詞曲秉、下劃線和破折號采蚀。在第一次使用這種標量之前,我們必須使用 my 關(guān)鍵字 聲明它承二。
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;
默認地,標量變量沒有特定的類型亥鸠,但是隨后我們會看到妆够,怎樣限制一個標量讓其能容納一個數(shù)字或任何其它類型。
聲明一個變量時也可不用初始化它的值: 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 的散列
散列(也叫做關(guān)聯(lián)數(shù)組)是一列鍵值對家妆,其中鸵荠,鍵是唯一的字符串,鍵值可以是任意值伤极。
散列以 % 符號開始蛹找。
#!/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
從散列中取回數(shù)據(jù)
#!/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
計算字數(shù)
#!/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;
# 創(chuàng)建散列
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" 函數(shù)也可以遍歷散列鍵.
#!/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
讀取整個文件內(nèi)容到標量變量中
Perl 6 有一個內(nèi)建模式來一次性吸入文件內(nèi)容, 那就是把整個文件內(nèi)容讀到一個標量變量中.
#!/usr/bin/env perl6
use v6;
my $filename = $*PROGRAM_NAME;
my $data = slurp $filename;
say $data.bytes;
Twigils 和特殊變量
Perl 6 有很多特殊變量.為了更容易地跟普通變量區(qū)分開,它們用一種叫做twigil的第二個前綴來標記塑荒。
通常,用戶自定義的變量有一個魔符($ @ 或%)在變量名前熄赡。
系統(tǒng)變量有額外的字符在魔符和變量名之間
Examples:
$*PROGRAM_NAME 包含當前運行的Perl 6 腳本的路徑.
$*CWD 是當前工作目錄的路徑。
$*IN 是標準輸入(STDIN).你可以使用 $*IN.get 讀入一行齿税。
你可以閱讀S28了解更多。
比較操作符
有兩種相關(guān)的比較操作符. 一種是比較數(shù)字炊豪,一種是比較字符串,基于 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
不能轉(zhuǎn)換字符串為數(shù)字:十進制數(shù)字必須以合法數(shù)字或點開頭
布爾表達式
布爾表達式 (邏輯操作符)
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讀取用戶輸入內(nèi)容知道用戶按下 Enter鍵。但是它只傳遞第一個換行之前的內(nèi)容
#!/usr/bin/env perl6
use v6;
my $name = prompt("Please type in yourname: ");
say "Hello $name"; #還不能處理漢字词渤,prompt是一個函數(shù)牵舱,其參數(shù)為提示信息
讀取文件內(nèi)容到數(shù)組中
當我們把調(diào)用slurp() 的結(jié)果放進數(shù)組中時,數(shù)組中將只有一個元素缺虐,該元素的值就是要讀取的文件中的所有內(nèi)容芜壁。如果你想讀取所有行到數(shù)組中不同的元素中,你需要使用 lines
函數(shù)高氮。
#!/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?
列表和數(shù)組
括號()中用逗號分隔的東西叫做列表慧妄。實際上你甚至不需要括號。 列表就是一組有序的標量值剪芍。例子:
#!/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); # 我們也能使用標量變量作為列表的元素
在大多數(shù)情況下,我們實際上甚至不需要括號.
列表賦值
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循環(huán)遍歷列表的元素
#!/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;
}
創(chuàng)建數(shù)組, 遍歷數(shù)組
你可以給一列值賦值給數(shù)組饱普。
在雙引號中數(shù)組不會進行插值运挫。這與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
數(shù)組元素 (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]";
數(shù)組賦值
#!/usr/bin/env perl6
use v6;
my $owner = "Moose";
my @tenants = "Foo", "Bar";
my @people = ($owner, 'Baz', @tenants); # 數(shù)組被展開:
say "{@people}"; # Moose Baz Foo Bar
my ($x, @y) = (1, 2, 3, 4);
say $x; # $x = 1
say "{@y}"; # @y = (2, 3, 4)
命令行選項
@*ARGS 數(shù)組由語言維護,它存儲著命令行的值冯袍。
#!/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 函數(shù)
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"];
創(chuàng)建數(shù)組, Data::Dumper, 調(diào)試打印
在Perl6 中創(chuàng)建數(shù)組跟在Perl5 中一樣匈挖,對于調(diào)試打印我們會使用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")
字符串中的數(shù)組插值
在雙引號字符串中颠猴,數(shù)組不再插值:
use v6;
my @names = "red","yellow","green";
say "@names"; # @names
你可以放心地寫下這樣的句子而不轉(zhuǎn)義 @ 符號:
use v6;
my @names = <Tom Cat>;
say "joe@names.org"; # joe@names.org
如果你確實要內(nèi)插數(shù)組的值关划,你必須將數(shù)組放在一對 花括號
中:
use v6;
my @names = < foo bar baz > ;
say "names: {@names}"; # names: foo bar baz
取數(shù)組元素, 魔符不變
當在Perl 6 中訪問數(shù)組的元素時,元素前的符號不會改變翘瓮!這對Perl 5 程序員來說會很奇怪贮折,但是長期看來它有優(yōu)勢。
use v6;
my @names = < foo bar baz > ;
say @names[0]; # foo
內(nèi)插一個數(shù)組元素
作為一個特殊情況资盅,一個數(shù)組元素能被內(nèi)插在雙引號字符串中而不使用花括號调榄。術(shù)語 post-circumfix
對于方括號
或花括號
來說是一個一般稱謂. 一般地,帶有前置符號的變量可以被內(nèi)插.
use v6;
my @names = < foo bar baz >;
say "name:@names[0]"; # name: foo
數(shù)組中元素的個數(shù)
在 Perl 6 中,推薦使用elems()
方法和相關(guān)的函數(shù)來得到數(shù)組的元素個數(shù)。實際上呵扛,我認為面向?qū)ο蟮膶懛ǜ烙^:
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 循環(huán)
Perl 5 中C風格的for 循環(huán)現(xiàn)在叫做loop缤灵,但是我不會在這兒展示它。
use v6;
for 1..3 -> $i {
say $i;
}
輸出為
1
2
3
這同樣對數(shù)組有效:
use v6;
my @names = < foo bar baz >;
for @names -> $n {
say $n;
}
輸出:
foo
bar
baz
順便提一下,這是你不用使用my聲明一個變量
的情況之一蓝晒。循環(huán)變量自動被聲明好了腮出,并且作用到for循環(huán)塊中。
遍歷數(shù)組的索引
如果你想遍歷數(shù)組的索引芝薇,你可以使用范圍胚嘲,從0一直到最大的索引值。最大索引值比數(shù)組元素的個數(shù)少1.你可以用 @names.elems -1
作為最優(yōu)的范圍 ,或者你可以使用 ^
符號告訴范圍排除最后一個值:
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()
方法會返回數(shù)組所有的索引洛二。即使你的數(shù)組含有‘空’值馋劈,即帶有undef
的元素,keys()
仍舊會包含這樣的元素的索引晾嘶。
split
split() 表現(xiàn)的就像Perl 5 中split的副本
一樣妓雾,但是默認行為不再應(yīng)用,無論如何变擒,你應(yīng)該查看文檔:
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
數(shù)字運算符
數(shù)字運算符可以用在標量值上面君珠。
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函數(shù)的兩個參數(shù):文件名和模式.為了打開一個文件讀取,模式需為 :r . 此函數(shù)要么返回一個存在標量變量中的文件句柄娇斑,要么失敗時返回 undef 策添。
$fh = open $filename, :r
一旦我們打開了一個文件句柄材部,我們可以使用 get 方法 ($fh.get) 從給定的文件中讀取一行。
你也可以連續(xù)調(diào)用 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中對存在的數(shù)據(jù)結(jié)構(gòu)進行操作是有趣的良狈,但是如果沒有輸入與輸出的話碟案,就會限制在真實世界中的用途壮啊。
因此,讀取文件內(nèi)容是一個明智的操作.
open
get
read
IO
lines
一行行讀炔稀(Read line-by-line)
open 函數(shù)會打開一個文件棵磷,默認情況下,你可以顯示地傳遞一個 :r 作為open函數(shù)的第二個參數(shù)晋涣。 Open會返回一個文件句柄仪媒,即一個IO類的實例。
get 方法會從文件讀取并返回一行谢鹊,末尾的新行會自動被移除算吩。 (Perl 5 開發(fā)者也可以認為 get 方法自動調(diào)用了chomp操作.)
my $fh = open $filename;
my $line = $fh.get;
你也可以在一個while循環(huán)中讀取文件的所有行。 與 Perl 5相反, 在這個while循環(huán)中佃扼,對是否定義沒有隱式地檢測.你必須在條件語句中顯示地添加單詞defined.否則偎巢,讀取操作將在第一個空行處停止。
my $fh = open $filename;
while (defined my $line = $fh.get)
{
say $line;
}
在for循環(huán)中使用 lines
方法可能更具有Perl-6風格兼耀。 lines 方法會依次讀取文件的每一行压昼,然后將讀取到行賦值給變量 $line
,然后執(zhí)行代碼塊。
my $fh = open $filename;
for $fh.lines -> $line {
say $line;
}
寫文件
為了寫入內(nèi)容到文件我們首先要開啟 :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
賦值時的方法調(diào)用
在Perl 6 中它擴展了點操作符的功能梧躺,允許在對象上進行方法調(diào)用似谁。想想下面的例子。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
賦值時調(diào)用函數(shù)
這也同樣可以用于函數(shù)中塞琼,就如 $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
這甚至可以有效地使用逗號操作符向數(shù)組中壓入更多值。
my @a = (1, 2, 3);
@a ,= 4;
@a.say;
反轉(zhuǎn)關(guān)系操作符
等號(==)操作符在Perl6 中用于比較數(shù)字禁舷,eq用于比較字符串彪杉。 The negated version are the same just with an exclamation mark ( ! ) in front of them. 所以它們看起來就是 !== 和 !eq.
幸運的是毅往,那些都有它們的快捷寫法,可以寫為!=和ne派近。
其他操作符也有相應(yīng)的反轉(zhuǎn)版本攀唯,所以你可以寫 !>= ,它的意思是不大于 (對于數(shù)字) 并且你可以寫!gt 渴丸,對于字符串來說是一樣的. 我沒有全部攤出我們?yōu)槭裁葱枰@個侯嘀。
一個我能明白的優(yōu)點是如果你創(chuàng)建了一個叫做I的操作符,然后你會自動得到一個看起來像!I 的操作符谱轨,那是它的反轉(zhuǎn)戒幔。
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
反轉(zhuǎn)操作符
反轉(zhuǎn)操作符會反轉(zhuǎn)兩個操作數(shù)的意思. 所以就像交換 $b cmp $a
中參數(shù)的值,你可以寫為 $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);
# 檢查數(shù)字是否是遞增順序
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
字符串操作
自動將字符串轉(zhuǎn)換為數(shù)字
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! '
字符串函數(shù) - 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
字符串函數(shù) - substr
字符串函數(shù): 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開始知道結(jié)束
say $z;
$z = substr $s, *-4; # $z = tree
say $z;
$z = substr $s, *-4, 2; # $z = tr
say $z;
值在給定的列表中嗎
怎樣找出一個給定的值是否在一些值的中間错沃?這跟SQL中的IN操作符相似。
在 Perl 6 中雀瓢,有一個 any() 函數(shù)枢析,其功能與SQL 中的IN 關(guān)鍵字相似。讓我們看看它如何工作:
它是一個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標量的內(nèi)容相比較刃麸,如果它們中的任意一個為真醒叁,表達式即為真。
Perl 6 中的三元操作符
旁注: ?? !! 對Perl 6 的三元操作符泊业。它語法如下:
CONDITION
??
VALUE_IF_TRUE
!!
VALUE_IF_FALSE
;
它仍然是weekday嗎?
更完整的例子讓我們來看當所有這些值都不匹配時會發(fā)生什么:
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
使用小于號比較數(shù)字
下個例子我們將會看到any函數(shù)能用于其它諸如小于號操作符的比較運算符上:
use v6;
my @numbers = (6, -12, 20);
say any(@numbers)< 0
?? "There is a negative number"
!! "No negative number here";
結(jié)果為:
There is a negative number
你也可以使用其它操作符.
假使沒有負數(shù)它也有效:
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
其它關(guān)鍵字: none
, all
, one
還有其它函數(shù), 不僅僅是 any 函數(shù): (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
使用最合適的那個函數(shù)把沼。
更短的寫法
有時候你有一個值,你需要檢測它是否等于一個所列值中的任意一個:
use v6;
my $n = 12;
say ($n == 23 or $n == 42) ?? "ok" !! "not ok"; # not ok
使用 any 函數(shù)你可以這樣寫:
use v6;
my $n = 12;
say $n == any(23, 42)
?? "ok"
!! "not ok"; # not ok
any 函數(shù)也有一個單管道線的中綴操作符版本吁伺,所以你也能這樣寫:
use v6;
my $n = 12;
say $n == 23|42
?? "ok"
!! "not ok"; # not ok
交叉
這些關(guān)鍵詞和相關(guān)操作所做的實際上是創(chuàng)建了一種叫做Junction
的數(shù)據(jù)類型饮睬。它是一個標量,以一種無序的方式存儲著多個值篮奄。跟集合類似捆愁。
第一個例子也可以這樣寫:
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";
這里我們創(chuàng)建了一個junction而非數(shù)組,然后使用該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表現(xiàn):
any(23, 42)
any(24, 43)
Functions on Junctions
你也可以將 junctions 作為參數(shù)傳遞給函數(shù)昼丑。 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 中宜雀,任何非字母數(shù)字字符
需要被轉(zhuǎn)義。
在下個例子中控妻,我們需要轉(zhuǎn)義 -
符號:
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";
}
有效州袒,打印匹配。
新特殊字符
#
現(xiàn)在是一個特殊字符弓候,代表注釋,所以當我們真正需要一個#
號時郎哭,需要轉(zhuǎn)義:
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 "
轉(zhuǎn)義后正確:
use v6;
my $str = 'abc # 123';
if $str ~~ m/(\#.)/ {
say "match '$/'";
}
Perl 6 的匹配變量
每次一有正則操作,一個叫做 $/
的本地化變量被設(shè)置成實際匹配到的值菇存。
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 中一系列整數(shù)的操作
Perl 6 中一系列整數(shù)的操作
my $x = 23;
my $z = 27;
for $x .. $z -> $i {
say $i;
}
會打印出期望的數(shù)字 23, 24, 25, 26, 27 .
C風格的循環(huán)
C風格, 有3部分的for循環(huán)在Perl 6 中也是可行的但不推薦恬惯。
my $x = 23;
my $z = 27;
loop (my $i = $x; $i <= $z; $i++) {
say $i;
}
序列
在Perl 6 中用 for 循環(huán)每隔2個數(shù)遍歷也是可以的,我們使用3個 . 而非2個 . 這里我們談?wù)摰氖切蛄卸欠秶?br> 我們設(shè)置序列的前兩個元素和序列的上限.
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;
}
會報錯酪耳。(現(xiàn)在已修正, 打印 1刹缝,3葡兑,5,7)
Perl 6 中的標量赞草、數(shù)組、散列如何插值
標量吆鹤、數(shù)組和散列插值
將標量放在雙引號中會進行插值厨疙,就跟Perl 5 中一樣:
use v6;
my $name = "Foo";
say "Hello $name, how are you?";
這會打印:
Hello Foo, how are you?
數(shù)組和散列不是這樣進行插值的,在字符串中疑务,任何放進花括號
中的東西都會被插值沾凄,所以如果你有一個數(shù)組梗醇,您能這樣寫:
use v6;
my @names = <Foo Bar Moo>;
say "Hello {@names}, how are you?";
to get this output:
Hello Foo Bar Moo, how are you?
這里的問題是基于輸出結(jié)果你不知道數(shù)組是有3個元素還是2個:
"Foo Bar" 和 "Moo", 或僅僅一個元素: "Foo Bar Moo".
內(nèi)插表達式
上面的就不是個問題! 在用雙引號引起來的字符串中撒蟀,你可以將任何表達式放在花括號
中叙谨。表達式會被計算,其結(jié)果會被插值:
你可以這樣寫:
use v6;
my @names = <Foo Bar Moo>;
say "Hello { join(', ', @names) } how are you?";
輸出如下:
Hello Foo, Bar, Moo how are you?
然而這依然沒有準確地顯示有幾個值保屯,這顯得稍微復雜了手负。
作為旁注,萬一你更喜歡面向?qū)ο蟮拇a姑尺,你也可以像下面這樣寫:
say "Hello { @names.join(', ') } how are you?";
結(jié)果一樣.
調(diào)試打印
對于基本的調(diào)試目的竟终,做好使用數(shù)組的 .perl
方法:
say "Names: { @names.perl }";
那會打印:
Names: Array.new("Foo", "Bar", "Moo")
假使你想同時看到變量名呢切蟋?那你可以依賴數(shù)組在雙引號字符串中不插值這點這樣寫:
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
這分不清哪些是鍵什黑,哪些是值. 對于調(diào)試目的,你最好用 .perl
方法:
say "%phone = { %phone.perl } ";
會打印:
%phone = ("foo" => 1, "bar" => 2).hash
插值多維數(shù)組
use v6;
my @matrix = (
[1, 2],
[3, 4],
);
say "@matrix = { @matrix.perl }";
輸出:
@matrix = Array.new([1, 2], [3, 4])