Lesson 15 of 15

Putting It All Together

Putting It All Together

Let's combine everything you have learned: scalars, arrays, hashes, loops, subroutines, and string operations.

Example: Word Frequency Counter

sub count_words {
    my ($text) = @_;
    my @words = split(" ", $text);
    my %freq;
    foreach my $w (@words) {
        my $lower = lc($w);
        if (exists $freq{$lower}) {
            $freq{$lower} += 1;
        } else {
            $freq{$lower} = 1;
        }
    }
    return %freq;
}

Example: FizzBuzz

The classic interview problem -- combining loops, conditionals, and modulo:

for my $i (1..15) {
    if ($i % 15 == 0) {
        say "FizzBuzz";
    } elsif ($i % 3 == 0) {
        say "Fizz";
    } elsif ($i % 5 == 0) {
        say "Buzz";
    } else {
        say $i;
    }
}

Your Task

Write a subroutine fizzbuzz that takes a number $n and prints FizzBuzz from 1 to $n. Call it with 15.

JS Transpiler loading...
Loading...
Click "Run" to execute your code.