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

Monks, I'm stumped. I'm using the following to take a record title and create a filename from the title. It works but if the title has more than 8 words the filename ends up being short, and without the .html. I cannot seem to find where this is breaking down. If the title is shorter than 8 words it works fine, but 9 words and it fails.

The filename should be something like: 2018-09-25-this-is-a-sample-title.html.

I also do some checking to see if the filename is already used and add a "2" to the end of the filename.

$base_title = $title; $base_title =~ s/[^\w| ]/ /g; #Remove non-alphanumeric characters a +nd replace them with spaces $base_title =~ s/ {2,}/ /g; #remove multiple spaces $add_date = $dateadded; @words = split (/ /, $base_title); $filename = $dateadded."-" . join("-",@words) . ".html"; $filename_base = $filename; $filename_base =~ s/\.html//g; # check to see if filename is being used $SQL = "SELECT * FROM $database_table WHERE filename = '$filename' +"; &Do_SQL; $i=2; while ($pointer = $sth->fetchrow_hashref){ $filename = $filename_base."$i.html"; $i++; $SQL = "SELECT * FROM $database_table filename = '$filename'"; &Do_SQL; } $SQL = "INSERT INTO $database_table (filename) VALUES ('fi +lename')"; &Do_SQL;

Any help would be appreciated. It might be simple, but I'm stumped. Thanks!

Replies are listed 'Best First'.
Re: Creating filenames from title
by Corion (Patriarch) on Sep 25, 2018 at 20:08 UTC

    Personally, I want filenames to be mostly ASCII, so I wrote Text::CleanFragment to create URLs or filenames that don't contain accents or other stuff. Mostly, it forces the text to match  /^[-._A-Za-z0-9]*$/ , which I find pleasing and which doesn't really have problematic characters for filesystems or HTML.

    The module differs from your approach by converting (say) Motörhead to Motorhead, instead of Mot rhead, , and by compressing multiple dashes into one.

Re: Creating filenames from title
by Laurent_R (Canon) on Sep 25, 2018 at 22:01 UTC
    I would tend to avoid inserting spaces into file names. They create all kinds of difficulties, especially if you work with different operating systems or even simply different platforms.
Re: Creating filenames from title
by htmanning (Friar) on Sep 25, 2018 at 19:41 UTC
    Sorry, I found it. If anyone else has an issue like this check the database field length. It was cutting off the filename.