Peter Stuifzand

Spreadsheet import

osfameron asked:

I’ve been prototyping ways for customers to import data into our system. […] How would you tackle this task? Is there even an elegant way to do it imperatively?

He is trying to import data into his system, but his information is not all in a flat structure. It looks like this:

Name        Price   Tag
Brie        2.00    Dairy
                    Cheese
                    Food
Chablis     5.00    Wine
                    Alcohol
                    Drink

As you can see the there is a start row and a few extra data rows after that.

The program that I would write to import this data looks like this:

use strict;
use warnings;
use Product;
use Data::Dumper;

my @products;

while (<>) {
    if (my ($name, $price, $tag) = m/^(\w+)\s+(\d\.\d{2})\s+(\w+)$/) {
        my $product = Product->new(product => $name, price => $price);
        $product->add_tag($tag);
        push @products, $product;
    }
    elsif (($tag) = m/^\s+(\w+)$/) {
        my $product = $products[$#products];
        $product->add_tag($tag);
    }
}

print Dumper(\@products);

In the way that I have written this code it doesn’t need two pushes. Pushing it on the array is the first thing that I do after creating the product. The other parts of the code that need to refer to the product that was added last use the last product in the array.

My program is different to osfamerons code by using regexes, but this allowed my to actually test my code.

© 2023 Peter Stuifzand