On Sun, Jan 18, 2015 at 4:00 PM, Mike <ekimduna...@gmail.com> wrote:
> So I've got a text file in a multi column format (three columns), each
> column is separated by a single space. Here is a snippet for reference:
>
> artless base-court apple-john
> bawdy bat-fowling baggage
> beslubbering beef-witted barnacle
>
> I want to be able to randomly select a word from the first column, then from
> the second column, then from the third column, and concatenate them to
> together into a single string. Here's the code I currently have, but I'm
> stuck:
>
> sub gen_ins {
>     open(FH, '<', 'insults2.txt') or die "[-] ERROR: Can't find insult
> list.";
>     my @cols = split (" ", <FH>);
>     print "$cols[0]";
>     close FH;
> }
>
> gen_ins();
>
> When currently run, gen_ins() will print out the first word of the given
> column: $cols[0], $cols[1], or $cols[2]. How can I access the rest of the
> words below the first?
>

'perldoc -f split'  and look at the 2nd argument. It's a string. What
you've written
internally becomes  split(" ", $_=<FH>).  Remember 'context'?  It's in play here
too because that'll just pick up the first line of the file. See:
perldoc perldata.

Actually,  you could do this until you grasp what's happening:

open(F,"rationale.txt")  or die $!;
my @lines = <F>;
my $line = $lines[ int(rand( $#lines ) ) ];  # perldoc -f rand
my @words = split(" ",$line) ;
say $words[0];

Then, if you're counting calories and want a one-liner:

perl -E 'open(F,"rationale.txt");@l=<F>; say +( split(" ",
$l[int(rand($#l))]) )[0]'

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to