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

Hi, I've created a very basic Perl script to generate combinations of words:

use strict; use warnings; use Algorithm::Combinatorics qw(combinations); my $strings = [qw(Word1 Word2 Word3 Word4)]; my $iter = combinations($strings, 2); while (my $c = $iter->next) { print "@$c\n"; }

How would I go about using words from a .txt file rather than manually adding them (GGGG CCCC...). I understand the basics of opening and reading (line-by-line) files in perl but I am not sure how to use this data within the above script. My .txt file is essentially:

Word1 Word2 Word3 Word4

And so on. Can I use something like:

open (DATA, "text.txt"); @Test = <DATA>; close DATA;

To open/read it? Not sure how to then get Perl to use the loaded data. Can anybody offer any assistance? Thanks!

Replies are listed 'Best First'.
Re: Using imported .txt file with Algorithms::Combinatorics
by LanX (Saint) on Jan 08, 2014 at 12:26 UTC
    open (my $filehandle, "<", "text.txt") or die "Problem opening text.tx +t: $!"; @test = <$filehandle>; close $filehandle; chomp @test;

    should do, if every line has exactly one entry.

    Untested ...

    see open for more examples and perlintro#Files-and-I/O¹ for general pointers to even more documentation.

    Do you need suggestions for good Perl books?

    Cheers Rolf

    ( addicted to the Perl Programming Language)

    updates

    ¹) strange that perlintro doesn't mention chomp

      Thank you! Suggestions for good books would be great. I need something that builds up the foundations more than anything. Perl seems like a really amazing language but I haven't come to grips with an efficient way to learn it - and have instead just been looking at and editing existing scripts. For now, I am simply curious to see how you could then take @test and use it to replace

      my $strings = [qw(GGGG CCCC TTTT AAAA)];

      such that the words in the .txt file are combined. Would you mind showing me?

        in a complicated way:

        my $strings = \@test;

        easier

        @$strings = <$filehandle>;

        ATM I'm in a hurry ... others might recommend you books. =)

        Cheers Rolf

        ( addicted to the Perl Programming Language)