in reply to Re: How do I read this line of code?
in thread How do I read this line of code?

Thanks for your answer, this helps a lot.

Now, what if there is no shift:

$buff .= $_ for "\n", '  ' x ( $level - 1), @pre_push;

I would expect every element in @pre_push to have a newline and spaces in front of it, but when I test it, using the following code, I see that the newline and spaces are only added once.

my @pre_push; my $level = 2; my $buff = ''; push (@pre_push, "test"); push (@pre_push, "test2"); for my $string ("\n", ' ' x ( $level - 1 ), @pre_push) { $buff = $buff . $string; } print $buff;

Output:

  testtest2

Replies are listed 'Best First'.
Re^3: How do I read this line of code?
by GrandFather (Saint) on Sep 29, 2011 at 09:46 UTC

    The for (used as a statement modifier) in the original line of code takes a list which consists of three entries: newline, some number of spaces, and an item shifted off an array. If you remove the shift the last entry in the list becomes another list (the elements in the array) appended to the list containing the first two items. There is nothing there to prefix each element following the first two elements of the list with the concatenation of the first two elements which is what your expectation implies.

    If you want to achieve that you have to rewrite the statement a little. Consider:

    my @pre_push = qw(test test2); my $level = 2; my $buff = ''; $buff .= $_ for map {"\n" . (' ' x ($level - 1)) . $_} @pre_push; print $buff;

    Prints:

    test test2

    The map concatenates the prefix to each element of the array before passing the modified list on to the for.

    Alternatively you could move the prefix concatenation to the assignment to the left of the for to give the same result and remove the map:

    $buff .= "\n" . (' ' x ( $level - 1)) . $_ for @pre_push;
    True laziness is hard work
Re^3: How do I read this line of code?
by choroba (Cardinal) on Sep 29, 2011 at 09:46 UTC
    The loop iterates over the newline, spaces and the array. If you want to iterate it over the array and add newlines fore each member of the array, you can do
    $buff .= "\n" . (' ' x ($level - 1)) . $_ for @pre_push;