| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- #!/usr/bin/env perl
- # x is a global variable which can be accessed from other namespaces
- # ex: if we were in the namespace ONE::TWO then access 'a' with ONE::TWO::W
- # it is mandatory for globals to be uppercased
- global W = 2
- # fibonacci sequence with ret value cached
- fun fibonacci(n) is cached {
- n < 2 ? n : _F_(n - 1) * _F_(n - 2)
- }
- # forever loop
- forever {
- "Hello World".say
- }
- # async forever loop
- async forever {
- ["Hello", "World"].each{ .uc.shuffle + _ }
- }
- # fun fibonacci asyncronously
- async fibonacci(10)
- # Working with blocks
- LABEL: {
- say "block one"
- # recurse to the current block
- _BLOCK_ if "one".shuffle(3) = "one"
- # recurse to the current block too
- _LABEL_ if "one".shuffle(3) = "one"
- {
- say "block two"
- # recurse to LABEL
- _LABEL_ if "two".shuffle(4) = "two"
- # recurse to the current block
- _BLOCK_
- }
- }
- ## Numbers
- 3.times{ ... } # ...: unimplemented
- ## Hash
- # declare a hash and store it in a lexically scope variable
- let bhash = {one: 2, two: 1} # or
- let ahash = Hash.new(
- 2 -> two,
- 3 -> "this three",
- one -> 1,
- ) # can replace '->' with ','
- # declaring a code/block
- let code = {
- let(k, v) = (_[0], _[2])
- say "#k, #{v isa Num ? v + 1 : v.uc }"
- }
- code(k, v) foreach k,v in ahash
- ahash.each_kv{ a.say; b.say }
- # _ is a topic variable
- hash.keys{ (_ + .lc).say }
- ahash{one}.say # accessing elements
- ahash{one, 2, 3}.each{ ... } # returns an array
- ahash{one, 2, 3} = ["One", 2, "ThReE"] # change values
- let key = "Hello"
- say ahash{key} if ahash.exists(key)
- del key # delete lexical var 'key'
- ## Arrays
- let array = ["one", 2, 3] # or
- let barray = Array.new("one", 2, 3)
- array.say
- array.each{ ... }.grep{ ... }
- let r = 3..4 # returns an array of values ranging from 3 to 4
- r.each { .say }
- # access values
- barray[0].say
- array[2..4].each({...})
- # lvalue
- array[0..1] = qw(i j)
- 'a'..'z'.each{ ahash.exists(_) && .say }
- ## Complex data structures
- let wtf = {
- one -> [ { two -> 3, three -> 4 }, [qw(a b c d)] ],
- two -> do { ... },
- three -> True ? [ { one -> 1, two -> 2 } ] : do { ... },
- }
- let b = [wtf, True]
- ## Working with Files
- const file = "/path/to/file"
- <file>.each_line{ .uc.say } # <a> open file "a" for reading if exists and return the File object
- <>.each_line{ ... } # read from standard input
- # flow constructs
- while (True) { ... }
- foreach v in array { ... }
- # classes
- class Person { ... }
- class Student << Person {
- has class is rw
- has notes is ro
- # multiple dispatch
- multi method get_nodes(v) {
- self.notes.each{ _ > v}
- }
- multi method get_nodes(v, k) {
- self.notes.each{x < _ < k}
- }
- }
|