amoser has asked for the wisdom of the Perl Monks concerning the following question:

This node falls below the community's threshold of quality. You may see it by logging in.
  • Comment on Pulling lines from a file into an array?

Replies are listed 'Best First'.
Re: File Handeling
by benn (Vicar) on May 22, 2003 at 18:23 UTC
    /me posts his first ever Mr Grumpy-Monk reply

    Homework alert. Although hardburn has kindly provided you with a bunch of code, it's the kind of code that 10 minutes digging around this site would have produced. Honestly mate - it's for your own good :) Sure - you could sail through on other peoples code and get the piece of paper you need - *or* you could learn something. Trust me - it's more fun the second way.

    Cheers
    Ben.

Re: File Handeling
by hardburn (Abbot) on May 22, 2003 at 18:14 UTC

    You just open each file handle in turn and keep pushing the lines on to the array:

    my @lines; open(IN1, '<', 'file1') or die $!; while(my $line = <IN1>) { chomp $line; push @lines, $line; } close(IN2); open(IN2, '<', 'file2') or die $!; while(my $line = <IN2>) { chomp $line; push @lines, $line; } close(IN2); my $size = scalar(@lines); # Get the size of the array

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated

Re: File Handeling
by Limbic~Region (Chancellor) on May 22, 2003 at 18:18 UTC
Re: File Handeling
by arthas (Hermit) on May 22, 2003 at 18:53 UTC
    A nice idea would be an array of hashes, which is an alternative to the excellent two-array solution hardburn explained you.
    use strict; open(QUESTIONS, '<', 'questions.txt') or die $!; open(ANSWERS, '<', 'answers.txt') or die $!; my @quiz; while(my $question = <QUESTIONS>) { my $answer = <ANSWERS>; chomp ($question); chomp ($answer); push @quiz, { 'q' => $question, 'a' => $answer, }; } close(QUESTIONS); close(ANSWERS); my $nquestions = scalar(@quiz);
    You can then access to the elements as follows:
    for my $i(0..$nquestions-1) { print $quiz[$i]{'q'}."\n"; print $quiz[$i]{'a'}."\n"; }
    Michele.
Re: Pulling lines from a file into an array?
by nite_man (Deacon) on May 23, 2003 at 07:28 UTC
    I would like to suggest you use module Tie::File for access the lines of a file via a Perl array:
    tie @array, 'Tie::File', $fname or die 'Couldn\'t open file: '.$!; $array[1] = 'blah'; # line 1 ine the file is now 'blah' print $array[3]; # display line 3 of the file # do something untie @array; # all finished
    Advantage of this method is that the file is not loaded into memory.
          
    --------------------------------
    SV* sv_bless(SV* sv, HV* stash);