in reply to local() for scalar file slurping

local provides a limited form of scoping for package variables. When you want to change a package variable (such as $/) temporarily, use local, not a temporary variable. That way, the variable's value will be restored even if the scope is exited using die.

{ local $var; ...; }
is very similar (as observed when $var is magical) to
{ my $anon = $var; undef $var; ...; $var = $anon; }
except $var = $anon; will execute even if the scope is exited using die. (Also, it's probably more efficient).

By the way,
my $foo = do { local $/; <> };
is quite neat, but it requires twice as much memory as
my $foo; { local $/; $foo = <>; }

Replies are listed 'Best First'.
Re^2: local() for scalar file slurping
by apotheon (Deacon) on Jul 28, 2006 at 22:57 UTC

    requires twice as much memory

    Why?

    print substr("Just another Perl hacker", 0, -2);
    - apotheon
    CopyWrite Chad Perrin

        That's odd. Definitely let me know if you figure it out.

        print substr("Just another Perl hacker", 0, -2);
        - apotheon
        CopyWrite Chad Perrin