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

It could save many keystrokes for one-liners:
$a=$magichash{'/path/to/file/fn'}; # now $a contains file contents $magichash{'/path/to/file/fn'} =~ s/foo/bar/g; # please guess...
Of course only limited usage is wanted (no large files, and so on, may be read-only usage)

Is there exists such a module? On CPAN?

Because if it does not exist, it should be, to simplify writing one-liners, and may be for quick slurping of small files.

  • Comment on Is there exist a module to provide access to a file via hashes using TIE ?
  • Download Code

Replies are listed 'Best First'.
Re: Is there exist a module to provide access to a file via hashes using TIE ?
by BrowserUk (Patriarch) on Sep 23, 2004 at 23:16 UTC

    Tie::TextDir


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    "Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon
      thanks!

        Your sample usage seems to want to do an inplace edit on a file. You can do that with the -i flag....

        perl -pi.bak -e 's/this/that/g' infile

        This will modify infile and write a backup of original to infile.bak No .ext == no backup.

        cheers

        tachyon

Re: Is there exist a module to provide access to a file via hashes using TIE ?
by BUU (Prior) on Sep 24, 2004 at 01:38 UTC
    For shame, no one has mentioned IO::All?
    my $file = io('file')->slurp; $file =~ s/change/s/; $file > io('file');
Re: Is there exist a module to provide access to a file via hashes using TIE ?
by ihb (Deacon) on Sep 23, 2004 at 23:16 UTC

    There is File::Slurp which provides read_file(), write_file(), append_file(), and read_dir(). I often use it for both long and short programs. It's one of my favourite can't-live-without modules. I think it pretty much does what you want, but with another interface, and you need to perhaps use an intermediate scalar.

    ihb

    Read argumentation in its context!

Re: Is there exist a module to provide access to a file via hashes using TIE ?
by TedPride (Priest) on Sep 24, 2004 at 00:49 UTC
    Very simple to implement, actually -
    %magichash; &magic(\%magichash, '/path/to/file/fn'); print $magichash{'/path/to/file/fn'}; sub magic { my $handle; if (open($handle, $_[1])) { $_[0]->{$_[1]} = join('', <$handle>); close($handle); return 1; } }
    Note that the sub also returns a bool response, so you can tell if it successfully loaded the file or not.