CJ7
CJ7

Reputation: 23275

How to sanitize string for unix filename?

In perl, how can I sanitise a string to be used as a filename in a Unix based system?

eg. AX/1234/BB would obviously need to have the forward slashes dealt with in some way.

Are there any modules that deal with this issue?

Upvotes: 1

Views: 707

Answers (2)

ikegami
ikegami

Reputation: 385847

A unix file name can contain any character except / and NUL, so the following makes sure $fn is a valid file name.

warn("Invalid file name") if $fn =~ m{[/\0]};

But you didn't say you wanted to detect bad file names; you said you wanted to sanitize them. However, you didn't say how. Perhaps you wish to replace the illegal characters with others? If so, you can use the following:

$fn =~ s{[/\0]}{_}g;

Upvotes: 2

CJ7
CJ7

Reputation: 23275

The File::Util function escape_filename does exactly this.

use File::Util;
$result = escape_filename($str);

Upvotes: 2

Related Questions