in reply to Extract first word from certain lines in a file
#!/usr/bin/perl use strict; use warnings; local $/ = "\nProduct:\n"; while ( <DATA> ) { my @line = map { /Product:/ ? () : (split " ")[0] } split /\n/; print join ' + ', @line; print " = ", common( \@line ), "\n"; } sub common { my $line = shift; my $short = 65536; for ( @$line ) { $short = length $_ if length $_ < $short }; my $index; for ( --$index ; $short-- ; --$index ) { my $str = substr($line->[0], $index); for ( @$line ) { return substr($_, ++$index) if substr($_, $index) ne $str; } } } __DATA__ Product: redball This is for Mike. greenball This is for Dave. Product: smallbox This is for apples bigbox This is for orange
Cheers - L~R
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Extract first word from certain lines in a file
by ihb (Deacon) on Oct 26, 2004 at 16:25 UTC |