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

I have raw data like this:

Washington
New York
Louisiana
Georgia
Texas
Iowa
etc.

and I want to turn it into an array:
qw (Washington, New York ....);

I can do it manually but it is a fuzz to do it every time.
Is it perhaps possible with while (< DATA >)? How to input raw data into a perl script?

Replies are listed 'Best First'.
Re: from txt file to array
by Discipulus (Canon) on Jun 21, 2017 at 19:09 UTC
    yes it is possible using chomp and push while iterating DATA

    You can also assign an undef value to $/ and assigning directly <DATA> to an array. Infact the diamond operator in list context will fill your array.

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Re: from txt file to array
by stevieb (Canon) on Jun 21, 2017 at 19:10 UTC

    Into an array:

    chomp (my @data = <DATA>); print "$_\n" for @data; __DATA__ one two three

    Iterating over it as a file handle without saving into an array:

    while (<DATA>){ chomp; print "$_\n"; } __DATA__ one two three

      And with saving it to an array is easy too:

      my @myarray; while (<DATA>) { chomp; push @myarray, $_; }

      (As you probably know, or that perldoc perlvar will tell you, $_ is a predefined Perl variable that implicitly refers to the most-recently entered source line and that is often used in situations like this for purposes of brevity.)

      (Personally, I prefer to write code "pedantically," like this, because it is easy to understand and to modify later.)

        And with saving it to an array is easy too:

        Ummm, first three lines of my post that you replied to:

        Into an array:
        chomp (my @data = <DATA>); print "$_\n" for @data;

        That saves the whole thing to an array without an explicit loop, *and* uses the default var $_ to show the implicit nature when looping over data...

        If you see being "pedantic" (i.e. explicit) as something good (I sometimes do too), then you simply should avoid punctuation variables and implicit arguments altogether:
        my @myarray; while (my $item = <DATA>) { chomp $item; push @myarray, $item; }
        But here my taste would be a more functional idiom:
        my @myarray = map { chomp; $_ } <DATA>;
Re: from txt file to array
by 1nickt (Canon) on Jun 21, 2017 at 19:35 UTC

    Use a module for common tasks. Someone has already written and optimized the code, figured out the edge cases, fixes bug reports ...

    Path::Tiny is my go-to tool for file handling. To read in lines into an array, use lines(). Chomp if you want, handle encoding if you want.

    1193233.txt

    Washington New York Louisiana Georgia Texas Iowa

    1193233.pl

    use strict; use warnings; use feature 'say'; use Path::Tiny; # imports path() my $file = '1193233.txt'; my @list = path( $file )->lines({ chomp => 1 }); say scalar @list . ' items'; say 'item: ' . $_ for @list;

    Output:

    $ perl 1193233.pl 6 items item: Washington item: New York item: Louisiana item: Georgia item: Texas item: Iowa

    Hope this helps!


    The way forward always starts with a minimal test.
Re: from txt file to array
by thanos1983 (Parson) on Jun 22, 2017 at 09:13 UTC

    Hello WisDomSeeKer34,

    Although the fellow Monks have replied to your question, I would like to add something extra.

    On your question you are asking on how to process one file, and the monks have provided you the answer. I would like to add here that while loop is faster than straight opening a file in an array but also to add using a hash to keep track of the content of multiple files.

    Sample of benchmark script and hash solution commented:

    #!usr/bin/perl use strict; use warnings; use Data::Dumper; # use Benchmark qw(:all) ; # WindowsOS use Benchmark::Forking qw( timethese cmpthese ); # LinuxOS my @preserved = @ARGV; =Hash Of Arrays my %HoA; while (<>) { chomp; push @{ $HoA{$ARGV} }, $_; } continue { close ARGV if eof; } print Dumper \%HoA; __END__ $ perl test.pl in.txt out.txt $VAR1 = { 'in.txt' => [ 'Sample of text line 1', '', 'Sample of text line 2' ], 'out.txt' => [ 'Sample of text line 1 second file', '', 'Sample of text line 2 second file' ] }; =cut sub while_loop { my @output; @ARGV = @preserved; # restore original @ARGV while (<>) { chomp; push @output, $_; } continue { close ARGV if eof; } return; } sub file_to_array { @ARGV = @preserved; # restore original @ARGV chomp (my @data = <>); close ARGV if eof; return; } my $results = timethese(10000000, { Array => \&file_to_array, While => \&while_loop }, 'none'); cmpthese( $results ); __END__ $ perl test.pl in.txt in2.txt Rate Array While Array 115513/s -- -4% While 120846/s 5% --

    Maybe you are not interested in opening multiple files (today) but what about (tomorrow)?

    Update: One minor thing also to add here. Always always remember to close your file handles. Why? read this: Why do we need to close filehandles?.

    Update2: Minor thing updating @ARGV to $ARGV in Hash Of Arrays (HoA) solution.

    Hope this helps, BR.

    Seeking for Perl wisdom...on the process of learning...not there...yet!
Re: from txt file to array
by karlgoethebier (Abbot) on Jun 22, 2017 at 10:16 UTC

      Karl, I also share the general opinion that, particularly in these politically tumultuous times within the USA, the wisdom of such a signature-line might be ... Meditated upon.   That’s all.   I am not sure that it belongs in the Monastery, no matter what your intentions and feelings might be.   Politics is not a topic that I am accustomed to seeing, in any form, here.   And I kinda like it that way . . .

      Hello Karl. With all due respect, this is a software discussion forum. There is a time and a place for displaying your political opinions. This is not it. We would appreciate it if you displayed you political opinions elsewhere. Thank you.

      "Its not how hard you work, its how much you get done."

        What someone puts in their signature is entirely up to them.

        How (or whether) you respond to someone's signature is entirely up to you.

        I'm reminded of a hobbyist computer network that I was a member of some time ago. Being comprised of people from around the world, it was only natural that disputes would arise from differences of opinion about politics, religion, methods of preparing barbecue, the virtues of superchargers vs turbochargers, etc etc.

        People would usually simmer down after somebody (eventually) brought up the two major tenets that members agreed to when joining the network:

        1. Thou shalt not excessively annoy others.
        2. Thou shalt not be too easily annoyed.

        When I find myself getting worked up over something someone has said online, I recall these words and try to act accordingly.

        Personally, I skip over sigs and would not have noticed karlgoethebier's sig if roho had not pointed it out.

        With all due respect, "we" have an equally hard time with punctuation and grammar errors in sigs.


        The way forward always starts with a minimal test.

        I thought about it and jumped to the conclusion that "we" must withstand my signature.

        Regards, Karl

        «The Crux of the Biscuit is the Apostrophe»

        Furthermore I consider that Donald Trump must be impeached as soon as possible

        "...We would appreciate it if you displayed you political opinions elsewhere..."

        Hello roho, i register this and think about it.

        It is not the first time i hear this and it seems that my signature had some other unpleasant impact.

        But may i ask who is "we"?

        Regards, Karl

        «The Crux of the Biscuit is the Apostrophe»

        Furthermore I consider that Donald Trump must be impeached as soon as possible

        With all due respect, this is a software discussion forum. There is a time and a place for displaying your political opinions. This is not it.

        Liberals tend to believe their views are "normal," so asking for anything else is asking for a favor. He won't change. So, i just mod down his posts when i come across them, as i would anyone with a political opinion where it does not belong. Quite a few monks have outspoken political views, but it is rare that they make it part of their signature.

        Other than that, he's a pretty cool monk.

Re: from txt file to array
by WisDomSeeKer34 (Sexton) on Jun 21, 2017 at 19:58 UTC

    Perfect. Thank you all.