in reply to Out of Memory in Perl

Also when i try just the following code with the new file it is giving some problems like my system gets frozen and all

open (my $fh, "<", "Google_1.txt"); my @file_array; while (my $line = $fh){ chomp($line); push (@file_array, $line); } print "@file_array \n";

Replies are listed 'Best First'.
Re^2: Out of Memory in Perl
by zentara (Cardinal) on Jul 08, 2012 at 16:55 UTC
    Hi, try wrapping $fh with the <> operator. Otherwise, you just keep setting $line to the $fh object, until you run out of resources.
    # wrong while (my $line = $fh){ # right while (my $line = <$fh >){
    Additionally, unless you need to process each line individually, it might be simpler to write
    open (my $fh, "<", "test.txt"); my @file_array = (<$fh>); print @file_array,"\n";

    P.S. Since you are dealing with big files, you might want to use ARGV's special line by line processing magic. That way, you never pull the whole file into memory. Google for perl ARGV magic.

    #!/usr/bin/perl use warnings; use strict; # use ARGV's magic @ARGV = "test.txt"; my @results; while ( <ARGV> ){ chomp $_; if ($_ =~ m/head/){ push (@results, $_); } } print "@results\n";

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku ................... flash japh
Re^2: Out of Memory in Perl
by frozenwithjoy (Priest) on Jul 08, 2012 at 16:55 UTC

    Your problem is (potentially) two-fold: with this snippet you are tying to read the entire file into memory (but actually, you are getting stuck in a neverending while loop because you use $fh instead of <$fh>). Are you doing something special with this that requires the entire file to be read in at once or just printing it to STDOUT (or another file handle)? If the latter, a simple fix is:

    open my $fh, "<", "Google_1.txt"; print $_ while <$fh>;

    One more thing... If the input file is small enough and you really do want to read it into an array for something other than printing, you can use something like this instead of your while loop:

    open my $fh, "<", "Google_1.txt"; my @file_array = <$fh>; chomp @file_array;

      I used the <$fh> but the line does not get saved in the array? It also does not print anything

        Can you show the new code with your changes please?