fbax
fbax

Reputation: 47

perl unlink fails for file with special characters

Unix system is hosting shared folders for Windows workstations. I wrote a script to delete old temp files that MS products create; but it does not work. I wrote this code snippet to reproduce the issue:

use strict;
use warnings;

 my $fn = '~$557.222 King Street.doc';
 system( 'touch', $fn );
 system( 'ls -l *.doc' );
 unlink '$fn' or warn "$! $fn";

This script produces:

-rw-r--r--  1 fbax  fbax  0 May 18 21:33 ~$557.222 King Street.doc
No such file or directory ~$557.222 King Street.doc at ../qTest.pl line 8.

I tried many many variations; they all failed. How can I make unlink delete this file?

Upvotes: 0

Views: 280

Answers (2)

ikegami
ikegami

Reputation: 386371

'$fn' produces the three-character string $fn rather the value of variable $fn. Replace

unlink '$fn'

with

unlink $fn

Upvotes: 2

brian d foy
brian d foy

Reputation: 132858

When I'm testing lines such as unlink or rename, I'll often start by using print instead so I can see the arguments before I do something stupid. With that you'd immediately see the problem:

# unlink '$fn' or warn ...
print '$fn' or warn ...

This is one place I get to use $,, the variable that holds the string that print puts between arguments ($" is what double quoted strings use, which is different):

 # unlink @items or warn ...
 local $, = ' ';
 print @items or warn ...

Upvotes: 0

Related Questions