Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

perl - How to handle filenames with spaces?

I use Perl on windows(Active Perl). I have a perl program to glob the files in current folder, and concatenate them all using dos copy command called from within using system()...

When i execute, this gives a dos error saying "The system cannot find the file specified." It's related to the spaces in the filenames I have.

This is the perl code :-

@files = glob "*.mp3";
$outfile = 'final.mp3';
$firsttime = 1;
foreach (@files)
{

    if($firsttime == 1)
    {
       @args = ('copy' ,"/b ","$_","+","$outfile", "$outfile");
       system (@args);
       #system("copy /b '$_'+$outfile $outfile"); 
       $firsttime = 0;  
    }
    else
    {
       @args = ('copy' ,"/b ","$outfile","+","$_", "$outfile");
       system (@args);
       #system("copy /b $outfile+'$_' $outfile"); 
    }

}

glob returns a array of filenames in my current folder, Those file names have spaces in between them, so the array elements have spaces in between. When i use the system(...) to execute my copy command on those array elements using "$_" as shown above, it gives error as above.

I tried couple of ways in which I could call the system(...) but without any success.

I would like to know,

1] How can i get this working on files which have spaces in between them using the code above. How to 'escape' the white space in file names.

2] Any alternative solution in Perl to achieve the same thing. (Simple ones welcome..)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Stop using system() to make a call that can be done with a portable library. Perl has a the File::Copy module, use that instead and you don't have to worry about things like this plus you get much better OS portability.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...