0

How do i reformulate a string in perl?

For example consider the string "Where is the Louvre located?"

How can i generate strings like the following:

"the is Louvre located"
"the Louvre is located"
"the Louvre located is"

These are being used as queries to do a web search.

I was trying to do something like this:

Get rid of punctuations and split the sentence into words.
my @words = split / /, $_[0];

I don't need the first word in the string, so getting rid of it.
shift(@words);

And then i need move the next word through out the array - not sure how to do this!!

Finally convert the array of words back to a string.

KVK
  • 1
  • 3

3 Answers3

1
  1. How can I generate all permutations of an array in Perl?
  2. Then use join to glue each permutation array back together into a single string.
Community
  • 1
  • 1
Aristotle Pagaltzis
  • 112,955
  • 23
  • 98
  • 97
1

Somewhat more verbose example:

use strict;
use warnings;

use Data::Dumper;


my $str = "Where is the Louvre located?";

# split into words and remove the punctuation
my @words = map {s/\W+//; $_} split / /, $str;

# remove the first two words while storing the second
my $moving = splice @words, 0 ,2;


# generate the variations
my @variants;
foreach my $position (0 .. $#words) {

    my @temp = @words;
    splice @temp, $position, 0, $moving;
    push @variants, \@temp;

}

print Dumper(\@variants);
jira
  • 3,890
  • 3
  • 22
  • 32
0
my @head;
my ($x, @tail) = @words;
while (@tail) {
    push @head, shift @tail;
    print join " ", @head, $x, @tail;
};

Or you can just "bubble" $x through the array: $words[$n-1] and words[$n]

foreach $n (1..@words-1) { 
    ($words[$n-1, $words[$n]) = ($words[$n], $words[$n-1]);
    print join " ", @words, "\n";
};
Dallaylaen
  • 5,268
  • 20
  • 34