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

I'm having what seems like an odd issue with the push function in a foreach loop.. Basically I want to parse an array looking for a particular regex in each element, and if that regex exists I want to push that element to a new array. When I implement this in practice the foreach loop works, the if condition works, but the push function seems to only push the first match? I'm including an example below to illustrate:
#!/usr/bin/perl use strict; use warnings; my @test = ('md1', 'md2', 'md3', 'md4'); my $test2 = ""; my @test3 = (); foreach my $line (@test) { if ($line =~ /md/) { push @test3, $line; } } printf @test3;
In this example, @test3 ends up being a single element array with element[0] being "md1". I was wondering if anyone could point me to documentation showing why this would happen, and possibly a fix? I've had no luck finding the cause.

Replies are listed 'Best First'.
Re: Seemingly odd issue with push in foreach loops?
by hdb (Monsignor) on Apr 23, 2015 at 21:15 UTC

    Check the documentation of printf. The first argument is supposed to be a format string, which is "md1" in your example and therefore will not print anything else. Change printf to print or use Data::Dumper to inspect your array and you will see that your code works as expected.

Re: Seemingly odd issue with push in foreach loops?
by BrowserUk (Patriarch) on Apr 23, 2015 at 21:13 UTC

    Change: printf @test3; to: print @test3; and see what you get.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
    In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked
Re: Seemingly odd issue with push in foreach loops?
by einhverfr (Friar) on Apr 24, 2015 at 06:44 UTC

    btw you can replace your foreach loop with grep:

    @test3 = grep { /md/ } @test;

    or if you like to be verbose

    @test3 = grep {$_ =~ /md/ } @test;
Re: Seemingly odd issue with push in foreach loops?
by akio_outori (Initiate) on Apr 23, 2015 at 21:36 UTC
    Ah yes, that makes sense. Simple user error. Thanks for the fast reply!