Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Basic Perl Regular Expressions

by Anonymous Monk
on Nov 12, 2001 at 08:25 UTC ( [id://124738]=perlquestion: print w/replies, xml ) Need Help??

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

I am new to Perl and I was hoping someone could explain to me how to divide up a string in order to work with each individual word. I have to use a program opposed to a script.

Replies are listed 'Best First'.
Re: Basic Perl Regular Expressions
by dvergin (Monsignor) on Nov 12, 2001 at 08:33 UTC
    This is just the sort of thing Perl is great at. Here's a bit to get you started.
    #!/usr/bin/perl -w use strict; my $sentence = 'A sentence is just a bunch of words'; # Do the magic. my @words = split /\s/, $sentence; # That was it! Now show the results. foreach my $word (@words) { print "$word\n"; }
    And don't be shy about reading the docs that come with Perl. They are really quite good. The key one in this case (and for many beginner questions) is called 'perlfunc'.

    Also, check out the Tutorials on this site. Very nice. There is one on Split and join.

      You might want to split on /\s+/ to be more robust. This will match white space of more than one character.

      You could also split on /\b/ and then grep for word characters if you wanted a slightly different definition of a word. This would split words with hyphons and apostorphes which might or might not be what you want.

      @words = grep (/\w/, split (/\b/, $foo));

      -monkfish (The Fishy Monk)

Re: Basic Perl Regular Expressions
by Zaxo (Archbishop) on Nov 12, 2001 at 10:42 UTC

    Being magical, split " ", $string; is better yet. It trims leading and trailing space without leaving an empty slot in the array, as well as eating multiple spaces.

    After Compline,
    Zaxo

Re: Basic Perl Regular Expressions
by Zecho (Hermit) on Nov 12, 2001 at 09:14 UTC
    perlre has the full details on how all of this stuff works

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://124738]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (9)
As of 2024-04-19 13:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found