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

in the below code which ever is present first push or print is working,the second line is not coming into picture,is there a way I can push to array and print to a file at the same time?

open(my $FOLDERS, '+>', "dirs.log") or die $!; find(sub { push @folders, "$_" if -d $File::Find::name && !$seen{$_}++ +; print $FOLDERS "$_\n" if -d $File::Find::name && !$seen{$_}++; }, $cwd +);

Replies are listed 'Best First'.
Re: How to push and print at the same time?
by kennethk (Abbot) on Mar 22, 2011 at 15:38 UTC
    Is there some reason why you can't just use a traditional if block (Basic BLOCKs)?

    open(my $FOLDERS, '+>', "dirs.log") or die $!; find( sub { if (-d $File::Find::name && !$seen{$_}++) { push @folders, "$_"; print $FOLDERS "$_\n"; }, $cwd );

    Alternatively, since your push will always return true (a positive integer), you can create a compound statement with and, though that's getting a little cute I think.

    open(my $FOLDERS, '+>', "dirs.log") or die $!; find(sub { push @folders, "$_" and print $FOLDERS "$_\n" if -d $File:: +Find::name && !$seen{$_}++;
      push @folders, "$_" and print $FOLDERS "$_\n"
      without relying on the value from push is
      push(@folders, "$_"), print $FOLDERS "$_\n"
Re: How to push and print at the same time?
by ikegami (Patriarch) on Mar 22, 2011 at 16:03 UTC
    push @folders, "$_"
    should be
    push @folders, $_

    You are adding noise to your script to needlessly create a copy of the string.

Re: How to push and print at the same time?
by Ratazong (Monsignor) on Mar 22, 2011 at 15:40 UTC

    You want to have two times the same condition:

    if -d $File::Find::name && !$seen{$_}++;
    However you are changing the things you check due to the post-increment (++). Suspicious, isn't it? ;-)

    Hint: remove the ++ in the first line ...

    HTH, Rata
Re: How to push and print at the same time?
by wind (Priest) on Mar 22, 2011 at 15:53 UTC