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

I am busy converting a perl script into a CGI.. this snippet of perl code works fine;
open (FILE, $ARGV[0]) or die "unable to open file $!"; my $data = do {local $/; <FILE>; }; print $data;
So why doesn't this CGI alternative snippet not work??
$file_contents = $query->param('file'); $file_contents =~ m/^.*(\\|/\)(.*)/; my $name = $2; open (FILE, ">$name") or die $!; my $data = do {local $/; <FILE>; }; print STDOUT $data;
thanks monks

Replies are listed 'Best First'.
•Re: perl + CGI's
by merlyn (Sage) on Dec 13, 2002 at 15:42 UTC
    $file_contents =~ m/^.*(\\|/\)(.*)/; my $name = $2;
    Never ever use $1 or $2 unless it's in the context of having tested whether the match worked or not.

    Since that match could fail, you have no idea what's in $2 at this point. Could be from a previous match.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: perl + CGI's
by hiseldl (Priest) on Dec 13, 2002 at 15:44 UTC

    You need to print a header first.

    use CGI; my $q = CGI->new(); print $q->header(); [insert your code here]

    The header tells the browser what type of content to expect, and without it, it gets confused.

    What time is it? It's Camel Time!

(jeffa) Re: perl + CGI's
by jeffa (Bishop) on Dec 13, 2002 at 15:48 UTC
    One problem you have is you are opening the file that you are supposed to be reading in write mode in the second example. That's not good. :)

    Second, use File::Basename to get the basename (and don't forget your header!):

    use strict; use CGI qw(:standard); use File::Basename; my $file = param('file'); my $name = fileparse($file); print header; if (open (FILE, $name)) { my $data = do {local $/; <FILE>; }; print $data; } else { print "can't open '$name'"; }


    (the triplet paradiddle with high-hat)