Quantcast
Channel: Rohan Almeida's Blog » perl6
Viewing all articles
Browse latest Browse all 4

Solving the Balanced Brackets task using Perl 6 – Part 3

$
0
0

In my attempt to learn Perl 6, I decided to pick up random tasks from the Rosetta Code website to solve. Please view Part 1 and Part 2 of this post if you haven’t already.

In this part, we will cover how to receive user input from the shell (terminal), and how to create and use a Perl 6 module.

Receiving user input is fairly easy.

my $input = prompt "Enter the string to be checked: ";

Were you expecting something more complex? Sorry! You can just use the prompt function which will first print the supplied argument to standard output (the terminal in most cases), and wait for user input. After the user enters some characters to be checked for balancing, she presses the Enter key. This signifies the end of user input, and the $input variable will now contain the user supplied string. Note that the newline is automatically removed, so you don’t have to use chomp on $input.

In our previous posts we defined the check_balance subroutine which does the actual work of validating the balance of the brackets and returns True or False accordingly. Lets see how we can move this subroutine to a module. Modules are great when you need to organize related code into a single place as well as for code reuse.

If you wish you can read this article of mine on how to Create and use a Perl 6 module, or continue reading.

To create a module, you need to place your subroutine in a separate file. Lets get creative and name this file CheckBalance.pm6. Here’s what it looks like.

module CheckBalance;

sub check_balance(Str $b) is export returns Bool {

    my $num_opens = 0;

    for $b.comb -> $c {

        if $c eq '[' {
            $num_opens++;
        }

        if $c eq ']' {
            $num_opens--;
            if $num_opens < 0 {
                return False;
            }
        }
    }

    return $num_opens == 0;
}

This is the same subroutine we wrote in Part 1, except here notice the is export trait. This tells the module to export the check_balance subroutine into the caller’s namespace automatically.

Now in our script we can use the module.

use CheckBalance;

loop {
    my $input = prompt "Enter the string to be checked: ";
    say check_balance($input) ?? 'OK' !! 'NOT OK';
}

Notice the loop keyword. In Perl 6 the loop keyword is similar to the for loop in C. Except here we create a never ending loop. (You can use Ctrl+C to kill the script).

You can check out all the code on Github. I hope you learned something new in Perl 6. Have fun!


Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images