How to write a new line to the end of the file in Perl?

i am very new to Perl. i am using Ubuntu. i have a string call $string that contains following words "new line". i also have a data file as follows.

djfibjbet
etitrbjijbtr rrge     rgjierjegjeri
jerijg
kijij  jijij

i want to write my new line to my data file as follows.

djfibjbet
etitrbjijbtr rrge     rgjierjegjeri
jerijg
kijij  jijij
new line

Here is my code.

#!/usr/bin/perl
sub io
{
# usage:
# @array  = io('read',$file)
# $string = io('read',$file)
# io('write',$file,\$string)
# io('write',$file,\@array)

my($bit,$file,$data) = @_;

 if($bit eq 'read')
 {
    open IO,"< $file" or die "Cannot open $file for input: $!\n";
    my @file = <IO>;
    close IO;
    return wantarray ? @file :  join '', @file;
 }

 if($bit eq 'write')
 {
 open  IO,"> $file" or die "Cannot open $file for output: $!\n";
 print IO  ref $data eq 'ARRAY' ? @$data : ref $data eq "SCALAR"? $$data : ' ';
 close IO;
 }

}
    $string =`cat test.dat | grep  test`;
    io('write','/home/run/test.log',\ $string);

issue is, new line will replace all my old lines in the data file. how can i overcome this issue? can someone please help? :frowning:

Probably you need to open the output file for append mode, but you opened it for write mode.

Try

open  IO,">> $file" or die "Cannot open $file for output: $!\n";
1 Like

u are a god, thanks

---------- Post updated at 04:07 PM ---------- Previous update was at 02:46 PM ----------

so if i want to change,

io('write','/home/run/test.log',\ $string);

to

io('write','/home/run/<$name>test.log',\ $string);

how do i do that?
In other words, lets say i have XXXXXtest.log files, such as pretest.log, aftertest.log, badtest.log. so i want to use a string call name, so i can pick which file to write in to depending on the situation. Could you please tell me how to do that?

Not sure if I got you, hope this is what you were searching:

    $string =`cat test.dat | grep  test`;
    $ofile='/home/run/pretest.log';
    io('write',$ofile,\ $string);