Hi Steve,
On Thursday 20 Jan 2011 20:57:50 steve1040 wrote:
> I need to add 2 lines to a file and add the following text.
>
> ENTHDR|1|3.0
> STAGEHDR|Barcoded
>
> I don't have any idea how to do this in Perl
>
In UNIX and UNIX-like systems (including Windows), it is useful to think of a
file as a big sequence of octets, where you can overwrite or append data if
it's the same width, but you cannot insert stuff in the middle (or the
beginning) or remove stuff from inside easily.
The best way to prepend some data to the beginning is to write a new file and
then to move it on top of the existing file: (tested:)
[code]
#!/usr/bin/perl
use strict;
use warnings;
my $filename = shift(@ARGV);
my $new_fn = $filename . '.new';
open my $in, '<', $filename
or die "Cannot open $filename for reading - $!";
open my $out, '>', $new_fn
or die "Cannot open $new_fn for writing - $!";
print {$out} <<'EOF';
ENTHDR|1|3.0
STAGEHDR|Barcoded
EOF
while (my $line = <$in>)
{
print {$out} $line;
}
close($out);
close($in);
rename($new_fn, $filename);
[/code]
Note that you can also use file I/O abstractions such as Tie::File
( http://perldoc.perl.org/Tie/File.html ) or IO::All (
http://search.cpan.org/dist/IO-All/ ) to write it more succinctly.
Regards,
Shlomi Fish
--
-----------------------------------------------------------------
Shlomi Fish http://www.shlomifish.org/
Why I Love Perl - http://shlom.in/joy-of-perl
Chuck Norris can make the statement "This statement is false" a true one.
Please reply to list if it's a mailing list post - http://shlom.in/reply .
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/