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

I'm trying to run a while loop, after reading from a file. When I use variable, the while loop is not working. However when using absolute path, it is working fine. Please let me know of a way in which I can use the variable.
# my $filename='$mydir\file_detail.txt'; # open (FILE, '$filename'); open (FILE, 'D:\SiebelAdmin\CSS\file_detail.txt'); while (<FILE>) {}

Replies are listed 'Best First'.
Re: While is not working when using variable
by Anonymous Monk on Aug 31, 2015 at 08:32 UTC
    Add use autodie; to the top of your program, it will generate a message explaining what happened
      On using autodie, it is showing the error message that no such file or directory. But when harcoding the same path, the script is running.
      Can't open('FILE', '$filename'): No such file or directory at sblmaint.pl

        Try this:

        print '$filename', "\n"; print "$filename", "\n";

        And for more information, you can read this tutorial on quotes in perl.

        In addition to Eilys hint, try
        print $filename, "\n";
        Note that, if you have your complete filename in a variable, like in your OP (and as you should, as it eases debugging and error messages), quoting it in the open statement is superfluous.

        Besides, most Windows functions and many programs accept forward slashes, so you can write

        my $filename="$mydir/file_detail.txt"; open (FILE, "<", $filename);
        Update: corrected quotes - d'oh! Thanks AnomalousMonk!
Re: While is not working when using variable
by locked_user sundialsvc4 (Abbot) on Aug 31, 2015 at 12:27 UTC

    When you use single quotes to enclose a string, as you do in the now commented-out first line, symbols such as $mydir are not “interpolated.”   They are not seen as variable-names, but simply literal characters.   To get the behavior that you want, enclose the string in double quotes.

    (Yes, some other languages treat single vs. double quotes, with respect to interpolation, in precisely the opposite way.)