Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: Help with split() function

by wrinkles (Pilgrim)
on Mar 19, 2008 at 10:18 UTC ( #674970=note: print w/replies, xml ) Need Help??

in reply to Help with split() function

I'm working through some of these "Seekers" questions as a learning tool. This is my first perlmonks post. :)
To print one "word" per line, stripping out punctuation at the end, try this:
#!/usr/bin/perl use warnings; use strict; my $filename = shift; open my $TEST_FH, '<', "$filename" or die "Cannot open file $filename +\n$!\n"; while (<$TEST_FH>) { chomp; my @words = split; my @pmatch = grep {/p/i} @words; if (@pmatch) { foreach (@pmatch) { s/[^\w]$//; print "$_\n"; } } } close ($TEST_FH);

Replies are listed 'Best First'.
Re^2: Help with split() function
by driver8 (Scribe) on Mar 19, 2008 at 18:03 UTC

    Looks pretty good, but I'll make some suggestions. Instead of "[^\w]" you can use "\W". It means the same thing. Also putting "if (@pmatch)" before your "foreach" is redundant. If there is nothing in the array, it won't enter the loop. Here's my solution:

    while (<DATA>) { for (split /\W/) { print "$_\n" if /p/i; } } __DATA__ CPAN stands for comprehensive Perl Archive Network. ^ and $ are used as anchors in a regular expression. /pattern/ is a pattern match operator. Perl is very easy to learn. Enter 'H' or 'h' for help.

    It separates punctuation and other "\W" characters in the split statement. Then it skips any temporary arrays and just prints if the element contains a "p".


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://674970]
Discipulus now is read a book to my daugther time. Just after she and mother stop yelling in the bathroom
[Lady_Aleena]: See you later, Discipulus. Have fun reading to your daughter.
Discipulus still yelling..;=(

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2017-09-24 18:31 GMT
Find Nodes?
    Voting Booth?
    During the recent solar eclipse, I:

    Results (274 votes). Check out past polls.