R (Chandra) Chandrasekhar wrote:
Hello Folks,

I need to make a substitution in place for each element of an array, and I need to do this to two arrays. Currently the relevant code fragment (without pragmas) is:

--------
foreach my $element (@cddb_artist)
    {
    $element =~ s/^.*?([0-9,a-f]{8}):.*$/$1/;
    }
foreach my $element (@cddb_track)
    {
    $element =~ s/^.*?([0-9,a-f]{8}):.*$/$1/;
    }
--------

As Dr.Ruud said that could be written as:

    s/^.*?([0-9,a-f]{8}):.*$/$1/ for @cddb_artist, @cddb_track;

But you don't really need the anchors so:

    s/.*?([0-9,a-f]{8}):.*/$1/ for @cddb_artist, @cddb_track;

And if you are not worried about preserving the newline at the end you could do it like this:

    ($_) = /([0-9,a-f]{8}):/ for @cddb_artist, @cddb_track;


The above fragment seems to be a good candidate for generalizing into a subroutine.

sub my_sub_something {
    my $regex = shift;
    ( $_ ) = /$regex/ for @_;
    }

And call it like this:

my_sub_something( qr/([0-9,a-f]{8}):/, @cddb_artist, @cddb_track );


But it would probably be simpler just to use the for statement above.




John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order.                            -- Larry Wall

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to