Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Cannot print line

by nimpoura (Initiate)
on Nov 28, 2014 at 12:30 UTC ( [id://1108644]=perlquestion: print w/replies, xml ) Need Help??

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

Hello, I wrote the code below in order to get the first line of a txt file
use strict; use warnings; open (IN, "/home/nikol123/indri-5.6/runquery/trec7_4collections.txt") +or die; while (my $file = <IN>){ my @rows = split(/\n/, $file); print "$rows[0]\n"; } close IN;
Instead,it prints the whole txt and in the end refers this error: "Use of uninitialized value $rows[0] in concatenation (.) or string at /home/nikol123/tryperl2.pl line 8, <IN> line 59." Why this code is not functional? Thank you in advance

Replies are listed 'Best First'.
Re: Cannot print line
by choroba (Cardinal) on Nov 28, 2014 at 12:50 UTC
    Your code has a problem.
    my $file = <IN>

    reads in the first line of the file. You can just

    print $file;

    and be done. Instead, you split the line on newlines (there can't be more than one) and assign the result to an array. And, you repeat this for each line of the file (that's why you get the whole file on the output). I'm not able to get the uninitialized warning.

    Update: The warning means the line was empty, therefore there was nothing to split it into.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Cannot print line
by ww (Archbishop) on Nov 28, 2014 at 13:13 UTC

    For (IMO) the most likely meaning of the message you quote, Ln 59 of your data file is the second of two lines, each of which contains an newline and nothing else.

    And there is a more idiomatic (because it's more concise) way to get must the first line:

    use strict; use warnings; open (IN, "1108644.txt") or die; my $line = <IN>; print "$line\n"; close IN;

    ... and that won't care a lick about line-endings at the bottom of the file.

    updated by s/jmust/must/; above.


    ++$anecdote ne $data


Re: Cannot print line
by davido (Cardinal) on Nov 28, 2014 at 17:49 UTC

    open my $in_fh, '<', '/home/nikl123/indri-5.6/runquery/trec7_4collecti +ons.txt' or die $!; print scalar <$in_fh>;

    This will open a file and print the first line. You don't need a loop to read the first line of a file, and you don't need to split on newlines if you only read one line. In fact, you don't even need to print a newline explicitly, as each line of a file will end in one, except for the last line (unless the first line is the last line).

    Or how about this?

    use IO::All; print io('/home/nikl123/indri-5.6/runquery/trec7_4collections.txt')->g +etline;

    Dave

Re: Cannot print line
by poj (Abbot) on Nov 28, 2014 at 13:34 UTC
    Maybe this is what you intended.
    #!perl use strict; use warnings; my $infile = "trec7_4collections.txt"; open IN, '<', $infile or die "Could not open $infile $!"; my @rows = <IN>; close IN; print $rows[0];

      Re poj's contribution -- it works (and, ++ for following the OP's code while correcting it). But it seems unnecessarily complicated in comparison with suggestions in prior answers. On the face of the OP's problem, there's no need to use an array here.




      If you didn't program your executable by using mechanical switches to toggle-in the binary, it wasn't really programming!

      Thanks a lot!!
Re: Cannot print line
by stevieb (Canon) on Nov 28, 2014 at 15:36 UTC

    Although the issue has been solved in a few different ways, I'd like to point out that one should be using the three-argument form of open (I always prefer to use a variable as opposed to bareword too):

    my $filename = "/path/to/filename.txt"; open my $fh, '<', $filename; or die "Can't open the file $filename for reading: $!";

    EDIT: AnomalousMonk pointed out my brain fart usage of the filehandle instead of a variable in the die statement. Fixed

    -stevieb

      open my $fh, '<', "/path/to/filename.txt"
        or die "Can't open the file $fh for reading: $!";

      $fh is the filehandle object (or whatever the proper term is). Perhaps better as:
          my $filename = '/path/to/filename.txt';
          open my $fh, '<', $filename or die "Opening '$filename' for reading: $!";

        D'oh! Of course! Thanks for catching that :) My original comment has been corrected.

Re: Cannot print line
by talexb (Chancellor) on Nov 28, 2014 at 15:02 UTC

    I'm not sure what the objective is here, but if all you want is the first line of a file, you can just use head to achieve that ..

    tab@foo:~$ head -1 /etc/debconf.conf # This is the main config file for debconf. It tells debconf where to tab@foo:~$

    Alex / talexb / Toronto

    Thanks PJ. We owe you so much. Groklaw -- RIP -- 2003 to 2013.

Re: Cannot print line
by vinoth.ree (Monsignor) on Nov 28, 2014 at 16:00 UTC

    Hi

    As other monks given you the answer for your question.

    Here I am giving you the additional information.

    Always use the three-argument open.The modern version of this code is safer and clearer.

    Ex:
    open my $fh, '>', $filename # safer and clearer

    Moreover do not use while loop to read a single line from the file.

    If you want only the file content you can remove the new line from the line using chomp() function.


    All is well

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1108644]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2024-04-23 12:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found