stormCloud
stormCloud

Reputation: 993

How to loop over each word in an argument for perl

I'd like to have a perl program that I can call with something like:

perl myProgram --input="This is a sentence"

And then have perl print the output to terminal, in this format

word1 = This
word2 = is
word3 = a
word4 = sentence

I'm usually a c/c++/java programmer, but I've been looking at perl recently, and I just can't fathom it.

Upvotes: 1

Views: 3663

Answers (3)

rpg
rpg

Reputation: 1652

Please have a look at perldoc split().

foreach my $word (split (/ /, 'This is a sentence'))
{
     print "word is $word\n";
}

Edit: Added parentheses around the split call.

Upvotes: 1

zgpmax
zgpmax

Reputation: 2847

'split' doesn't handle excess leading, trailing, and embedded spaces. Your best bet is a repeated match over non-space characters, m{\S+}gso.

The first command-line parameter is $ARGV[0]. Putting that together we have:

#! /usr/bin/perl

use strict;
use warnings;

my @words = $ARGV[0] =~ m{\S+}gso;

for (my $i = 0; $i < @words; $i++) {
    print "word", $i + 1, " = ", $words[$i], "\n";
}

(I've iterated over the array using an index only because the question was originally framed in terms of emitting a rising value with each line. Ordinarily we would want to just use for or foreach to iterate over a list directly.)

Calling as:

perl test.pl ' This  is  a  sentence '

prints:

word1 = This
word2 = is
word3 = a
word4 = sentence

If you explicitly want to pick up input on a double-dash long option name then use Getopt::Long as described by Quentin.

Upvotes: 1

Quentin
Quentin

Reputation: 943561

Use Getopt::Long and split.

#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Long;

my $input = '';
GetOptions( 'input=s' => \$input );

my $count = 0;
for (split ' ', $input) {
        printf("word%d = %s\n", ++$count, $_);
}

Upvotes: 4

Related Questions