Search code examples
loopsfileperlio

How to write all values into a file from a loop, not just the last value?


I would like to write all server values in text file. But my output text file can only write one last value. For example, $theServer values are

as1tp.com
as2tp.com
as3tp.com
as4tp.com
as5tp.com

Instead of writing all those server values in output text file, I can only write one last value as5tp.com in my text file. Below is my code. How do I write all values into tier1.txt file?

use strict;
use warnings;
my $outputfile= "tier1.txt"
my $theServer;      
foreach my $theServernameInfo (@theResult){   

    $theServer = $theServernameInfo->[0];   
    print "$theServer\n";
    open(my $fh, '>', $outputfile) or die "Could not open file '$outputfile' $!";
    print $fh "$theServer";
    close $fh;
    
}

Solution

  • The following code should work. As the commenters suggested, I inserted the missing semicolon. I moved open and close outside the foreach loop, so that the file is not overwritten at every loop iteration. Remember that you opened it in '>' mode (write, not append):

    use strict;
    use warnings;
    
    my $outputfile = "tier1.txt";
    open( my $fh, '>', $outputfile ) or die "Could not open file '$outputfile' $!";
    
    foreach my $theServernameInfo ( @theResult ) {   
        my $theServer = $theServernameInfo->[0];    
        print "$theServer\n";
        print { $fh } "$theServer\n";   
    }
    close $fh;