Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: writing to the top of a file

by coec (Chaplain)
on May 20, 2004 at 03:07 UTC ( [id://354839]=note: print w/replies, xml ) Need Help??


in reply to writing to the top of a file

Try this
#!/usr/bin/perl use strict; use warnings; use Tie::File; use Data::Dumper; my $file = "file.txt"; my @lines; #tie @lines, 'Tie::File', $file || die $!; tie @lines, 'Tie::File', $file or die $!; my @tmp = splice @lines; push @lines, <STDIN>; push @lines, @tmp; untie @lines;
Tie::File isn't a standard module but its easily installed as it is pure Perl (i.e. doesn't need a C compiler installed).

CC

Updated: changed '||' to 'or'.

Another update

Given that whatever solution you choose will be running from a web page (via CGI), have you given any thought file locking? What if multiple copies of the CGI script are running at the same time? You could potentially lose a lot of data...

Replies are listed 'Best First'.
Re: Re: writing to the top of a file
by neniro (Priest) on May 20, 2004 at 10:01 UTC
    unshift makes it simpler:
    #!/usr/bin/perl use strict; use warnings; use Tie::File; my $file = "file.txt"; my $insert = shift @ARGV; chomp $insert; my @lines; tie @lines, 'Tie::File', $file or die $!; unshift @lines, $insert; # more simple, isn't it? untie @lines;
    best regards,
    neniro
Re: Re: writing to the top of a file
by Somni (Friar) on May 20, 2004 at 03:23 UTC

    Tie::File is core as of perl 5.8.

Re: Re: writing to the top of a file
by BrowserUk (Patriarch) on May 20, 2004 at 12:11 UTC

    Using Tie::File this way will still need to read and write the whole file. This is much slower than simply reading to the end to get the last line.

    It also doesn't scale well for largish files, and doesn't address the concurrency issue.


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://354839]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2024-04-25 11:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found