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

I want to know of what I WANT to do is possible...

I am doing an HTML::TableExtract, and getting back some strings that I would like to be able to "clean" before they get pushed into the aray.

...snip.... foreach $ts ($te->table_states) { foreach $row ($ts->rows) { push( @array, ($$row[1] =~ s/[?\s,]+//g) ) if $$row[0] =~ /\S+/; } print join("\n", @array); }

The output currently is:

2 2 2

So it is doing some scalar silliness.. Here is the output without the =~ s/[?\s,]+//g portion:

$44,000 $202,050 $246,050

Thanks again in advance. =)

Replies are listed 'Best First'.
Re: Regex on array elements during push
by dragonchild (Archbishop) on Mar 22, 2004 at 19:12 UTC
    push @array, map { (my $x = $_) =~ s/[?\s,]+//g; $x } grep { /\S/ } $ts->rows;

    Nice and readable (at least to Juerd and me ... *grins*) And, yes, I actually have this construct in production code, sometimes 4 and 5 levels deep.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

      Except $ts->rows is returning an array of array refs. The first element of each referenced array is the one to check for non-spaces, and the second one is apparently the one to modify and push:
      push @array, map { $_->[1] =~ s/[\s?,]//g and $_->[1] if $_->[0] =~ /\S/ } $ts->rows;

      The PerlMonk tr/// Advocate
        That was the ticket!! Works perfectly. My understanding of "map" is a bit weak, so I need to disect what you did.. AWESOME!! Thank you!
Re: Regex on array elements during push
by QM (Parson) on Mar 22, 2004 at 19:00 UTC
    s/// returns the number of replacements, while m// will return the (portions of the) match. See perlop s/PATTERN/REPLACEMENT/.

    While it is possible to DWYW here, it gets complicated and ugly "all-in-one-line". Why not break it down into 2 or more lines, so the next Perler (which may be you) doesn't waste an hour and a bottle of Anacin 26 trying to debug it?

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

      I had tried to do a "foreach" on the elements in @array, but I kept getting error mgs, so I wasn't sure if I was trying to do something that couldn't be done.. I am still a newbie.. how would you do it?

      Thank you.