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

can someone tell me how to include speechmarks in a variable?
I'm tring to delete a file with long filename including spaces;

$filename="a long filename with spaces"; $command="rm /here/$filename";

I somehow want to pass rm "here/$filename" into $command. I don't want to use unlink.

Replies are listed 'Best First'.
Re: speech marks in variable
by davorg (Chancellor) on Dec 07, 2001 at 20:02 UTC

    A couple of solutions. The first escapes the quotes with a backslash, the second uses the generalised qq() operator.

    $command = "rm \"/here/$filename\""'; $command = qq(rm "/here/$filename");
    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: speech marks in variable
by broquaint (Abbot) on Dec 07, 2001 at 20:06 UTC
    That would be the quotemeta() function you'll be wanting
    $filename = '/some "really" long file name.txt' $cmd = 'rm '.quotemeta $filename; system($cmd);
    I assume you've got a *very* good reason for not using unlink() as it sort's out this sort of thing without a problem.
    HTH

    broquaint

Re: speech marks in variable
by Masem (Monsignor) on Dec 07, 2001 at 20:02 UTC
    Simply escape them with a backslash:
    $command = "rm \"/here/$filename\"";

    (And as an aside, why don't you want to use unlink? It's going to be a heck of a lot safer than using this type of code.)

    -----------------------------------------------------
    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
    "I can see my house from here!"
    It's not what you know, but knowing how to find it if you don't know that's important

      can't use unlink cos i'm using $command in an ssh session
Re: speech marks in variable
by japhy (Canon) on Dec 07, 2001 at 20:02 UTC
    Why don't you want to use unlink()? Sigh. I suggest: $filename =~ s/(\s)/\\$1/g

    Update: I solved the wrong problem.

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Re: speech marks in variable
by hakkr (Chaplain) on Dec 07, 2001 at 20:01 UTC
    escape speech marks for perl
    $var="\"";
    and you can escape spaces for the shell
    $filename="a\ long\ filename\ with\ spaces";