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

I am receiving text files for a web site that I am working on. The files are sent to me with names such as mlb_boxscore39$81.txt and mlb_boxscore1945$521. I am receiving them from a company that only sends them in that naming convention. I am using the following to try and open the file:
open (INPUT, "C:/mlb_boxscore107238$4820.txt") or die "Can't open file +";
When I try to open the file I get my statement "Can't open file". I know that the problem is the $. Does anyone know a way that I can run my script without changing the file names.

Replies are listed 'Best First'.
Re: Opening a Text File that contains $ in the name.
by chromatic (Archbishop) on May 11, 2001 at 01:29 UTC
    Use single quotes around the file name or escape the $ with a backslash.

    Perl is trying to interpolate a scalar variable into the string. You want a literal dollar sign instead.

Re: Opening a Text File that contains $ in the name.
by Albannach (Monsignor) on May 11, 2001 at 03:33 UTC
    It is good that you are checking the sucess of your open call, but as you discovered, your error message didn't help very much. Perl provides some more tools to help you though. Here's a way to do it that provides more explicit assistance when something goes wrong:
    use strict; use warnings; my $filename = "C:/mlb_boxscore107238$4820.txt"; open(INPUT, '<'.$filename) or die "Can't open $filename: $!\n";
    Which produces:
    Name "main::INPUT" used only once: possible typo at test.pl line 4. Use of uninitialized value in concatenation (.) at test.pl line 3. Can't open C:/mlb_boxscore107238.txt: No such file or directory
    Note the following:
    • use strict generated the message about INPUT only being used once, which is handy in case you typed while(<INPT>) later on
    • use warnings generated the warning about the uninitialized value at line 3, which would lead you to ask "what concatenation" and possibly then notice the $ inside double quotes made Perl look for a variable there. Just to keep things simple, I try to always use single quotes unless I really need interpolation. That also makes the double quotes act as flags to other readers, alerting them to interpolation.
    • the third line of output came from the die but this time it contains quite a bit more information than before
      • Perl's interpretation of the problematic filename (note no $ present)
      • The actual error message that what you asked for doesn't exist (more explicit than "can't open")

    I hope this helps!

    --
    I'd like to be able to assign to an luser