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

I have used undef $/; to read a file. after that i am using Mail::Sendr to send mail. Mail is not working for this undef $/; if i remove this line then mail is working fine. I want to make null after reading FILE. How can i do that?

Replies are listed 'Best First'.
Re: undef $/ to null
by ikegami (Patriarch) on Jul 18, 2009 at 05:44 UTC

    There's no null in Perl. Oddly enough, undef sets the value to: undef.

    Minimize the area in which you change $/ by using local. It even has the fortunate side effect of setting the localised variable to undef.

    { local $/; ... $/ is undef here ... } ... $/ is restored here ...
Re: undef $/ to null
by AnomalousMonk (Archbishop) on Jul 18, 2009 at 06:02 UTC
    I assume that what you want to do is read the entire contents of a file to a scalar in a single read operation. This is commonly referred to as "slurping a file".

    A common Perl idiom for this is (the change to  $/ is localized to the do block):

    my $filename = 'file.name'; open my $fh '<', $filename or die "opening $filename: $!"; my $contents = do { local $/; <$fh> };
    There is even a module: File::Slurp.
Re: undef $/ to null
by Marshall (Canon) on Jul 18, 2009 at 05:44 UTC
    1. I think you should read about local. Some stuff here:
    http://perl.plover.com/local.html#Marginal_Uses_of_Localized_Fileh

    2. I would be careful about re-defining the record separator, but I guess you have already figured that out!

    Update: See the ikegami post below. local has the behavior that previous value is restored when the local def goes out of scope. A local is not like a "my" or an "our" variable. It is a different critter. I caution the use of local. Great when you need it, but don't use unless you need it. This is more like "push the current value" and restore previous value when the localized var goes out of scope.