in reply to Re: return undef
in thread return undef

when i use print FILEHANDLE myfunction(); the file that is being sent from my function gets copied into FILEHANDLE. thats what i want it to do. however if there is an error myfunction() returns undef. my question is how do i check if it is returning the filehandle or undef? in order to copy the file or display the error message?

Replies are listed 'Best First'.
Re^3: return undef
by ysth (Canon) on May 23, 2005 at 02:57 UTC
    Ah, you've confused people with your terminology. You seem to mean that the function reads from a filehandle and returns the contents. Is this correct?

    If so, something like:

    my $filedata = myfunction(); if (defined $filedata) { print FILEHANDLE $filedata; } else { # handle error... }
    P.S. Showing some or all of myfunction() would really help us help you.
Re^3: return undef
by tlm (Prior) on May 23, 2005 at 02:55 UTC

    I think you are confusing the meaning of copying filehandles with that of copying the contents from one file to another.

    I am guessing that it is the latter that you really want. I assume that myfunction returns either an open read handle or undef. In this case, you can do something like

    my $in = myfunction(); if ( $in ) { print FILEHANDLE while <$in>; } else { # handle null-handle error; }

    the lowliest monk

      how would i return an open filehandle through a functon? aren't you supposed to send the contents of the file?

        Both are possible; it all depends what you want to do. Here's a function that returns an open read handle:

        sub rh { my $filename = shift; open my $in, '<', $filename or die "Couldn't open $filename for reading: $!\n"; return $in; } my $in = rh( 'somefile.txt' ); print while <$in>;

        If your myfunction returns the contents of a file, then see ysth's reply.

        the lowliest monk

Re^3: return undef
by holli (Abbot) on May 23, 2005 at 05:03 UTC
    There is a module for this: File::Slurp.


    holli, /regexed monk/