[Melbourne-pm] Scaling perl

Daniel Pittman daniel at rimspace.net
Sat Oct 3 21:20:22 PDT 2009


"ajthornton" <jdthornton at ozemail.com.au> writes:

> OK, I kept my promise to try to enjoy perl. I looked up some tutorials on
> text processing and cut and paste ane xample, before playing with it and
> coming up with:
>
> #!/usr/bin/perl
> $str = "The 34567744444444 foxes jumped over the ripe yellow pumpkin";
> $str2= "The spaceman is a mutt in a spiderman suit";
> $str3= "Melbourne Storm";
> $comma = ',';
> # returns ?
> print length ($str);
> print $comma;
> print length ($str2);
> print $comma;
> print length ($str3);

[...]

> The original example had only str and did not put output between commas;

If you have hand-written the name of each string variable then, yeah, life
sucks.  Assuming something sensible like an array of 20,000 strings, though,
your code would be roughly:

    my @strings = qw{one two three ... twenty-thousand};
    print join(", ", map { length } @strings), "\n";

[...]

> In short, for "real world" size tasks as above would the sourcecode be
> scalable? If so, how? Am I on the right track?

Hand-naming variables?  As many as any other language, which means that by the
time you are getting to ten or so you should look at using better data
structures or algorithms.

In my example, the "join" and "map" functions are the better algorithms:

join pastes together an array of strings with a bit of text between them,
which is exactly what you want to do to your three strings.[1]

map runs the same code on all the values in an array; in this case we
transform from the string to the length of the string.

It might be clearer to explain that map is, essentially, a loop like this:

    my @input = (...);
    my @output;
    foreach my $_ (@input) {
        # whatever goes in the middle is run here
        my $result = ...;
        # in this case = length($_);
    }
    @input = @output;

Regards,
        Daniel

Footnotes: 
[1]  print join(', ', $str, $str2, $str3);  works too.

-- 
✣ Daniel Pittman            ✉ daniel at rimspace.net            ☎ +61 401 155 707
               ♽ made with 100 percent post-consumer electrons
   Looking for work?  Love Perl?  In Melbourne, Australia?  We are hiring.


More information about the Melbourne-pm mailing list