0

I am using perl for the first time. I am trying to read a line from input file and store it in an array. Note that the the input file contains a single line with a bunch of words.

I tried using the following code:

open input, "query";
my @context = <input>;

But this gives a syntax error. How could i fix this?

1
  • 1
    Please give a working example, also provide what you have in "query". Or is this your example? Also what is the error message? Commented Jul 19, 2013 at 10:58

2 Answers 2

4

It doesn't give a syntax error. IT even works fine if there's only one line. The following will only get the first line even if there are more than one:

my @context = scalar( <input> );

But why wouldn't you just do

my $context = <input>;
Sign up to request clarification or add additional context in comments.

Comments

3

What is the syntax error? IMHO it writes none. But I would suggest some improvements

  1. Always use use strict; use warnings; as a first line! It helps to detect a lot of possible problems.
  2. Code has no error handling.
  3. Use variables for file handlers. Using bareword is deprecated.
  4. Open file for read if you need to only read from a file.
  5. Maybe the ending newlines would be removed form the array.
  6. If the file not needed to be kept opened it worth to close it. Here is not needed as exit will automatically close it implicitly, but it is a good practice to close the files explicitly.

So it could be:

#!/usr/bin/perl

use strict;
use warnings;

open my $input, "<infile" or die "$!";
my @context = map { chomp; $_;} <$input>;
close $input;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.