It may be that the problem lies not so much with the script itself, but the way you are calling it.

If you have a file named filename with spaces then you cannot pass it to a script with

script filename with spaces
because the shell is going to pass that as three separate arguments, and so your script will look for one file named filename, a second file named with, and then a third file named spaces — any of which may or may not exist, but in any case won't be the file you meant to specify, the single file named filename with spaces.

To pass the file to a script, it must therefore be quoted. The quoting rules depend on the environment you are using, but in general if you put double-quotes around the filename (whether or not it has spaces) you should be fine. On UNIXy systems, single-quotes work, as does "escaping" the spaces with backslashes:

"filename with spaces" # works more or less universally 'filename with spaces' # works a lot of places, but not in the Windows + shell. filename\ with\ spaces # ditto
And there may be other ways as well; check your system's documentation.

See also this Q&A entry: How do you open a filehandle to a DOS file which has spaces in the filename?


In reply to Re: How do I open a file in a path that has spaces in the name? by grinder
in thread How do I open a file in a path that has spaces in the name? by maslas

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.