Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to take the variable $page_data and skip (delete) all words less than 3 characters in length, and then put them back in another variable name $new_page_data with a space after every word. The output always just gives me the last word - moon. Thanks in advance.
print "Content-type: text/html\n\n"; $ignore = 3; $page_data = "the cow jump over the moon"; @text = split(/\s/, $page_data); foreach $line (@text) { $len = length($line); if($len < $ignore) { delete(@text[$line]); } else { print "$line "; $new_page_data = sprintf("%-5s", $line); } } print "<p>$new_page_data";

Replies are listed 'Best First'.
Re: Adding to variable with sprintf()
by eXile (Priest) on Apr 28, 2005 at 01:06 UTC
    $page_data = "the cow jump over the moon"; $new = join(" ", grep { length($_) > 3} split(/\s/, $page_data)); print $new;
    See perlfunc manpages of split,join and grep for how this works, basically:
    • 1. split makes an array of the original line
    • 2. grep filters for elements longer than 3 chars
    • 3. join glues them together
      Slightly cleaner:
      $new = join ' ', grep length > 3, split ' ', $page_data;
Re: Adding to variable with sprintf()
by fireartist (Chaplain) on Apr 28, 2005 at 09:17 UTC
    Just so you know, the reason your code didn't work was because the line
    $new_page_data = sprintf("%-5s", $line);
    should have been
    $new_page_data .= sprintf("%-5s", $line);
Re: Adding to variable with sprintf()
by gube (Parson) on Apr 28, 2005 at 03:45 UTC

    Hi try this,

    $ignore = 3; $page_data = "the cow jump over the moon"; @new1 = map{(length($_) > 3) ? $_ : (sprintf("%-5s", $_))} split(/\s+/ +, $page_data);
Re: Adding to variable with sprintf()
by eibwen (Friar) on Apr 28, 2005 at 05:08 UTC

    And with a regex:

    $page_data = "the cow jump over the moon"; $page_data =~ s/\b\w{1,3}\b//g; $page_data =~ s/^\s+//; $, = ' '; print split(/(?<=\w)\b\s*/, $page_data);

Re: Adding to variable with sprintf()
by Anonymous Monk on Apr 28, 2005 at 01:10 UTC
    That's some cool code thanks it worked great!