Examples
- Hello world
- Fibonacci numbers
- Reading from standard input
- Reading from a file
- Writing to a file
- Run a shell command
- Guessing game
- FizzBuzz
- Iterating over a string
- Iterating over a range
Hello world
You can echo
any value to the standard output stream:
echo "hello world";
Pyro also has a family of $print()
functions:
$println("hello world");
You can use format strings with these functions to interpolate variables:
var target = "world"; $println("hello {}", target);
Fibonacci numbers
Calculate the n-th Fibonacci number:
def fib(n) { if n < 2 { return n; } return fib(n - 1) + fib(n - 2); }
Reading from standard input
Read a single line from the standard input stream:
var line = $input();
Read in a loop from the standard input stream:
loop { $print(">>> "); var line = $input(); if line == null || line == "exit" { break; } echo "input was: " + line; }
Reading from a file
Read the content of a file into a string:
var string = $read_file("input.txt");
This is a convenience function — a $file
object provides more fine-grained control:
var file = $file("input.txt", "r"); var string = file:read_string(); file:close();
Writing to a file
Write a string to a file:
$write_file("output.txt", "Content for file...");
This is a convenience function — a $file
object provides more fine-grained control:
var file = $file("output.txt", "w"); file:write("Content for file..."); file:close();
Run a shell command
The $shell()
function takes a string arugment specifying the command to run.
It returns a two-item tuple containing the exit code as an integer and the output as a string:
var (code, output) = $shell("pwd");
Guessing game
The classic guess-a-random-number game:
var target = $std::prng::rand_int(10) + 1; loop { $print("Enter a number between 1 and 10: "); var guess = $input(); if guess == null || guess == "exit" { break; } if guess == $str(target) { echo "Correct!"; break; } else { echo "Wrong! Try again..."; } }
FizzBuzz
The classic interview question:
def fizzbuzz(n) { for i in $range(1, n + 1) { if i % 15 == 0 { echo "fizzbuzz"; } else if i % 3 == 0 { echo "fizz"; } else if i % 5 == 0 { echo "buzz"; } else { echo i; } } }
Iterating over a string
A string is a sequence of bytes. You can iterate over these individual byte values using the :bytes()
method:
for byte in "hello":bytes() { echo byte; }
This gives the following output:
104 101 108 108 111
Alternatively, you can interpret the string as a sequence of UTF-8 encoded characters and iterate over these characters using the :chars()
method:
for char in "hello":chars() { echo char; }
This gives the following output:
h e l l o
Iterating over a range
The $range()
function returns an iterator over a range of integers:
for i in $range(5) { echo i; }
This gives the following output:
0 1 2 3 4