http://www.perlmonks.org?node_id=1016661

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

My file word.txt contains multiple terms in the file.. Just examples in the file.. foo bar fish cat
open (file, @ARGV[0]); @strings = <file>;
@ARGV[0] will open the word.txt file
I'm trying to achieve @string = ('foo','bar','fish','cat'); Expect typing all the terms out, it is all in one file.

Replies are listed 'Best First'.
Re: read file from ARGV
by Kenosis (Priest) on Feb 02, 2013 at 07:24 UTC

    Try the following (assuming each word is on a separate line):

    use strict; use warnings; chomp( my @strings = <> ); print "$_\n" for @strings;

    Usage: perl script.pl word.txt

    Update: In case your words are separated by spaces like "foo bar fish cat one two three," even if there are multiple lines, try the following:

    use strict; use warnings; my @strings; while (<>) { push @strings, split ' '; } print "$_\n" for @strings;
Re: read file from ARGV
by 2teez (Vicar) on Feb 02, 2013 at 08:56 UTC

    @ARGV[0] will open the word.txt file

    @ARGV is the array that contains the command-line arguments intended for the script.
    In Perl Programming, to get the first element of an array(such as @ARGV), you use $ARGV[0], not @ARGV[0].
    Please note the usage of "$" and "@".
    Please also check What is the difference between $array[1] and @array[1]?

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me
Re: read file from ARGV
by nithins (Sexton) on Feb 02, 2013 at 07:33 UTC

    hope the below code will b helpful for you

    #!/usr/bin/perl use strict; use warnings; my @a; open (FH,'<',$ARGV[0]); #or @ARGV[0] while(<FH>) { push(@a,$_); } print "@a";

      Hi nithins,
      I think it would be a good practice to check the return of open function and to also close an opened filehandles like

      open my $fh,'<',$ARGV[0] or die "can't open file: $!"; ... close $fh or die "can't close file: $!";
      Except one is doinguse autodie qw(open close);

      If you tell me, I'll forget.
      If you show me, I'll remember.
      if you involve me, I'll understand.
      --- Author unknown to me