Look and say sequence (Perl)

From LiteratePrograms

Jump to: navigation, search
Other implementations: C++ | dc | Eiffel | Haskell | J | Java | Lua | OCaml | Perl | PHP | Python | Ruby | Scala | sed | sh

This program is a code dump.
Code dumps are articles with little or no documentation or rearrangement of code. Please help to turn it into a literate program. Also make sure that the source of this code does consent to release it under the MIT or public domain license.

This is a simple Perl program to generate look-and-say sequences such as the Conway sequence.

<<look_and_say_sequence.pl>>=
sub look_and_say {
	my $generator = shift;
	my $seq_length = shift;
	my @sequence = ($generator);
	for (my $i = 1; $i <= $seq_length; $i++) {
		my $val = $sequence[-1];
		my $nextval = "";
		my $char = substr($val,0,1);
		while ($char && $val =~ m/$char+/g) {
			$nextval .= length($&).$char;
			$char = substr($',0,1);
		}
		push(@sequence, $nextval);
	}
	return @sequence
}
@conway = look_and_say(3,10);
print join(", ",@conway);
Download code
Views