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

I'm not sure if I can phrase this correctly, so bare with me! There is a document that has a bunch of variable text here I need to capture into an array for further manipulation. I use m/// to match the first hit without a problem, but how do I make it match and store each item into an array? The document will be in the form of a variable. Thanks in advance!

Replies are listed 'Best First'.
Re: multiple matches with a regex
by toolic (Bishop) on Apr 11, 2009 at 02:21 UTC
    There are examples and explanations in the free documentation, such as perlretut.

    Without knowing the details of your problem, I will offer a small example of how to extract integers from a scalar variable into an array using the /g modifier:

    use strict; use warnings; use Data::Dumper; my $doc = 'hhh123 bbb 45 abc 999'; my @nums = $doc =~ /\d+/g; print Dumper(\@nums); __END__ $VAR1 = [ '123', '45', '999' ];

    Update: Fixed typo in doc link, pointed out by davido.

      There are examples and explanations in the free documentation, such as perlreftut.

      You probably mean perlretut (regular expressions tutorial), not perlreftut (references tutorial).


      Dave

Re: multiple matches with a regex
by repellent (Priest) on Apr 11, 2009 at 07:25 UTC
    Welcome to the Monastery :)

    String::Scanf may help.

    Your question is a little terse. Need more details. Please provide a sample text of your document and how you'd like to match it into an array, plus what code you have so far.
Re: multiple matches with a regex
by mhearse (Chaplain) on Apr 11, 2009 at 10:09 UTC
    This sounds a bit like homework...
    #!/usr/bin/perl use strict; use Data::Dumper; open FILE, "/tmp/stuff.txt" or die $!; my @contents = split /\n/, do { local $/; <FILE> }; close FILE; my @results = grep { /^here/ } @contents; print Dumper(\@results); __END__ [ contents of /tmp/stuff ] here hereitis hereitwas hereitwillbe thisaintit [ program results ] $VAR1 = [ 'here', 'hereitis', 'hereitwas', 'hereitwillbe' ];