CUFP
grep
I was watching the <i>Empire Strikes Back</i> this evening and I
wanted to see if I could write a sub to translate a normal
sentence into Yoda-speak (read: too much free time). So here it
is. I am welcome to suggestions, improvments, or more pivot words.
<readmore>
<br />
<br />
<code>
#!/usr/local/bin/perl -w
use strict;
my @sentences = ('I will teach you',
'The truth is out there',
'That is an Imperial shuttle',
'My husband is giant dork', #this is my wife's suggestion
'These fish are tasty'
);
foreach (@sentences) {
print yoda($_)."\n";
}
sub yoda {
my ($sentence) = @_;
my @pivot_words = qw/is be will show do try are teach have/;
# Find out if I have a pivot word and grab the one with the lowest index
my $pivot = (sort { $a->[1] <=> $b->[1]}
grep {$_->[1] > 0}
map { [" $_ ",index($sentence," $_ ")] } @pivot_words)[0];
#^^^^^^ ^^^^^^^
# Change to fix the problem [zdog]
# pointed out - THX [zdog]
# No pivot words
return $sentence if (!$pivot);
# Pivot the sentence
$sentence = substr($sentence,$pivot->[1]+length($pivot->[0]),length($sentence)).
" ".
substr($sentence,0,$pivot->[1]).
$pivot->[0];
# Clear leading spaces
$sentence =~ s/^\s+//;
# Sentence case
$sentence = ucfirst(lc($sentence));
}
</code>
<p><b>Update:</b> Fixed to handle pivot words inside another word.</p>
<p><b>Update 2:</b> Fixed the word boundry problem with a better solution. The new sub follows:</p>
<code>
sub yoda {
my ($sentence) = @_;
my @pivot_words = qw/is be will show do try are teach have/;
# Find out if I have a pivot word and grab the one with the lowest index
my $pivot = (sort { $a->[1] <=> $b->[1]}
# sort the lowest index to the top
grep {$_->[1] > 0}
# filter out non-matches
map{$sentence =~ /\b$_\b/ ? [$_,$+[0]] : [$_,0]} @pivot_words)[0];
# create an anon array in the format
# ['pivot word',index_of_where_it_is]
#
# @+ stores the indexes of the successful matches and does not
# require the gyrations that [pos] does
# No pivot words
return $sentence if (!$pivot);
# Pivot the sentence
$sentence = substr($sentence,$pivot->[1]).
" ".
substr($sentence,0,$pivot->[1]);
# Clear leading spaces
$sentence =~ s/^\s+//;
# Sentence case
$sentence = ucfirst(lc($sentence));
}
</code>
<br /><br />
<A HREF="/index.pl?node_id=133383&lastnode_id=1072">grep</A>
<table align="left" cellpadding="6"><tr>
<td bgcolor="#000000">
<font color="#33CC33"><tt>Unix - where you can throw the manual on the keyboard and get a command</tt></font></td></tr></table>