views:

106

answers:

3

Perl code fragment:

my $export = $doc;
$export =~ s:\.odt:\.pdf:;

How would this be written cleaner? Not simply what are 900 other ways to write it, TMTOWTDI.

+10  A: 

 

my ($export = $doc) =~ s{\.odt}{\.pdf};

UPDATE: That solution doesn't compile (note to self: test before posting on SO). Instead you could say

(my $export = $doc) =~ s{\.odt}{\.pdf};
mobrule
9 up votes did not notice the error.
C.W.Holeman II
+7  A: 

I go for [.] to match a literal period:

$export ~= s{[.]odt$}{.pdf};

Note that only the first half of the s/// call is a regular expression. The replacement is a normal string, and does not require a period to be escaped.

You might want to represent files as objects and not strings, though, with Path::Class.

jrockway
I think you mean \z, not $. $ is only rarely desirable.
ysth
+1 for the separator {} being a little easier for me to read than : and the removal of the escape sequence in the replacement string.
C.W.Holeman II
`\z` is the "I am a PBP fanboi" escape sequence.
jrockway
A: 

my %ext = ( 'odt' => 'pdf', etc... ); (my $export = $doc) =~ s{.([^.]+)$}{'.'.($ext{$1}||$1})}eg;

Todd Lehman