Lesson 14 of 15

Data Processing

Processing Structured Data

In real Perl programs, you often read data from files and process it line by line. We will simulate this by working with multi-line strings.

Processing CSV Data

my @lines = ("Alice,30", "Bob,25", "Carol,35");
foreach my $line (@lines) {
    my @fields = split(",", $line);
    say "$fields[0] is $fields[1] years old";
}

Building a Report

Combine arrays and hashes to transform data:

my @data = ("apple:3", "banana:5", "cherry:2");
my $total = 0;
foreach my $item (@data) {
    my @parts = split(":", $item);
    $total += $parts[1];
}
say "Total: $total";

Accumulating Results

sub sum_array {
    my @nums = @_;
    my $total = 0;
    foreach my $n (@nums) {
        $total += $n;
    }
    return $total;
}

Your Task

Process an array of "name:score" strings. Print each person's name and score, then print the average score.

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