[Melbourne-pm] Scaling perl

Jacinta Richardson jarich at perltraining.com.au
Sun Oct 4 08:11:57 PDT 2009


Daniel Pittman wrote:

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


The only change I'd make to the above, is to show explicitly how to do this 
using the strings John was using (and be explicit about the argument to length()):

	my @strings = (
		"The 34567744444444 foxes jumped over the ripe yellow pumpkin",
		"The spaceman is a mutt in a spiderman suit",
		"Melbourne Storm",
	);

	print join( ", ", map { length $_ } @strings ), "\n";

This should print "60, 42, 15" followed by a newline.

The above uses a lot of short-hand and can be written several ways.  For example 
  we can remove the map, using a foreach loop as Daniel mentioned:

	my @strings = (
		"The 34567744444444 foxes jumped over the ripe yellow pumpkin",
		"The spaceman is a mutt in a spiderman suit",
		"Melbourne Storm",
	);

	my @lengths;
	foreach my $string (@strings) {
		push @lengths, ( length $string );
	}

	print join( ", ", @lengths ), "\n";

we could also generate the string before printing it, if that would be useful:

	my $str_of_lengths = join( ", ", @lengths );
	print "$str_of_lengths\n";

but I'd only do this if we weren't planning to print it, but instead wanted to 
return it from a subroutine or put it into an email etc.


The advantage of using an array for this kind of thing is that the code 
automatically works if we add a few more strings to our array.  We don't have to 
create new variables or do any extra work.

All the best,

	J


More information about the Melbourne-pm mailing list