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

Monks, I'm using the following to create filenames. I was originally grabbing the first 3 words of the title but for SEO reasons, I want to grab the entire title, no matter how long. I commented out the 3 and made it 12, but now I end up with titles that have trailing dashes. If the title is 3 words long, I get a title separated by dashes, with 9 trailing dashes at the end. Where am I going wrong?
@words = split (/ /, $titleclean); $filename = $year."-".$mon; #for ($i=0; $i<3; $i++) { for ($i=0; $i<12; $i++) { $filename = $filename."-".$words[$i]; } $filename = $filename.".html";
Thanks. UPDATE: I ended up doing this. Is there a better way?
$filename =~ s/ /-/gi; $filename =~ s/--//gi; $filename =~ s/-\.html/\.html/gi;

Replies are listed 'Best First'.
Re: Creating filenames
by roboticus (Chancellor) on Apr 02, 2012 at 19:57 UTC

    htmanning:

    What you're doing wrong is assuming that all titles are going to have 12 words. Instead, try this:

    @words = split / /, $titleclean; $filename = "$year-$mon-" . join("-",@words) . ".html";

    The join bit in the middle tells perl to string @words together with a dash between each one.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

      I'd write the last statement as:
      $filename = join "-", $year, $mon, @words; $filename .= ".html";

        JavaFan:

        Yes, that's much cleaner than mine.

        ...roboticus

        When your only tool is join, all problems become a matter of selecting the proper delimiter.

      roboticus solution is far better than my suggestion.

      But it does give me the excuse for a tangential observation: If your titles contain as many as 12 words (and some of them are l...o...o...n...g words) you're going to end up with a $filename that's terribly long -- if they average 4 chars per word and you're using a four digit year and a three letter month, that's a filename nearly 70 chars long (and heaven knows what a full path might look like).

      Thanks. This works, but @ww makes a good point that I should count the number of words, stick it in a variable, then the loop doesn't have to go around 12 times. This seems to work:
      @words = split (/ /, $titleclean); $numwords+=@words; $filename = $year."-".$mon; for ($i=0; $i<$numwords; $i++) { $filename = "$year-$mon-" . join("-",@words) . ".html"; }
      Look okay?
        No.

        roboticus way goes around only as many times as there are words in the title.

Re: Creating filenames
by ww (Archbishop) on Apr 02, 2012 at 19:57 UTC
    You probably want to use a variable whose value is the number of elements in @words for the max (rather than the hard-coded '12'). As you've written it now, your for loop cycles 12 times (regardless of how many words were found in the title) and when $words[i] is empty, you get the trailing hyphens.