1

I have an issue with file reading in perl.

There is a following source:

use strict;
use warnings;

sub main()
{
    my @lines = file_read("test.c") or die;
    file_print(@lines);
}

sub file_read
{
    my $filename = shift;
    my @lines;

    open(FILE, "<", $filename) or die $!;
    @lines = <FILE>;
    return @lines;
}

sub file_print
{
    my @lines = shift();

    print("Total lines " . scalar(@lines) . "\n");

    foreach my $line (@lines)
    {
            print($line);
    }
}

And the following file:

/******************************************************************************

*                                                                             *

*                                                                             *

The output is:

Total lines 1
/******************************************************************************

What is wrong here?

The only thing that I can suppose that it reads file till 0x0A 0x0A ASCII symbols combination.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Alex
  • 9,891
  • 11
  • 53
  • 87
  • 2
    take a look at `File::Slurp` (see http://stackoverflow.com/a/206682/180100) –  May 08 '13 at 11:13

2 Answers2

4

The code shown is not the full or correct Perl program, nothing shown actually calls main. Also the sequence

my @lines;
open(FILE, "<", $filename) or die $!;
file_print(@lines);
@lines = <FILE>;

tries to print the lines before reading them.

I think the reason that only one line appears to have been read is in the statement my @lines = shift();. This does not get the whole array, only its first element. Try replacing sub file_print{...} with

sub file_print
{
    print("Total lines " . scalar(@_) . "\n");

    foreach my $line (@_)
    {
            print($line);
    }
}
AdrianHHH
  • 13,492
  • 16
  • 50
  • 87
0

You should probably pass an array reference for the subroutine file_print

file_print(\@lines);

Then in the subroutine :

$lines = shift;
@lines = @$lines;

This will do the job.

TLP
  • 66,756
  • 10
  • 92
  • 149
Nagaraju
  • 1,853
  • 2
  • 27
  • 46