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

Hi guys,

Is there a way to export a variable out of the foreach, I've googled it, but don't seems to find something

foreach my $hash_ref2 (@result2) { my $comment = $hash_ref2->{'comment'}; if ($comment =~ /^this is an automatic +comment/) { last; my $done = "1"; } } print $done;

thanks

Replies are listed 'Best First'.
Re: scalar out of a loop
by Corion (Patriarch) on Jul 21, 2014 at 14:16 UTC

    Maybe you don't want to export a variable out of the loop, but set an existing variable to a different value?

    my $comment= '- no comment found -'; foreach my $hash_ref2 (@result2) { $comment = $hash_ref2->{'comment'}; if ($comment =~ /^this is an automatic +comment/) { last; } } print $comment;
      No, but you're right that was not complete. I've updated my post.

        My answer is the same, except that you'd replace my $comment by my $done.

        Or maybe I misunderstood your question still.

Re: scalar out of a loop
by LanX (Saint) on Jul 21, 2014 at 14:41 UTC
    > Is there a way to export a variable out of the foreach, I've googled it, but don't seems to find something

    "Exporting" is something completely different, googling won't help here.

    Corion was right, but the concept you need to understand is called "scoping" of lexical ("my") variables.

    Have a look here: Coping with Scoping.

    HTH! :)

    Cheers Rolf

    (addicted to the Perl Programming Language and ☆☆☆☆ :)

Re: scalar out of a loop
by AnomalousMonk (Archbishop) on Jul 21, 2014 at 15:21 UTC
    c:\@Work\Perl\monks>perl -wMstrict -le "my $done = 'got stuff to do'; print qq{'$done'}; ;; for my $i (1 .. 4) { print $i; if ($i == 2) { $done = 'finished'; last; } } print qq{'$done'}; " 'got stuff to do' 1 2 'finished'

    Note that you need to execute last after setting ('exporting') the  $done flag, not before as in your most recently posted originally posted code.

      thank you all guys !
Re: scalar out of a loop
by Anonymous Monk on Jul 22, 2014 at 01:09 UTC
    As noted – define a variable, outside of the loop, and initialize it with a known value (even undef). When desired, give this variable a value and (if appropriate) jump out of the loop with last. Now, one way or the other, the variable that you've defined "has some value." And, this value isn't anyone's leftovers: it's got the value that you gave it.