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

Can somebody explain, why this code is working:
ls -o --full-time|perl -pe "s/\s{2,}/ /g; for (my $i = 1; $i <= 9; $i++) {s/\s/;/;}"
and this code is not working:
ls -o --full-time|perl -pe "s/\s{2,}/ /g; for (1..9) {s/\s/;/;}"

what it does: replace first 9 spaces with ";"
spec: perl, v5.8.8, OS WinXP SP2
execute in cmd prompt.

Thanks in advance ...

Cilid

Replies are listed 'Best First'.
Re: for loop syntax ...
by davorg (Chancellor) on Mar 21, 2007 at 10:25 UTC

    There is a difference between your two loops.

    for (my $i = 1; $i <= 9; $i++) { s/\s/;/; }

    In this loop, the variable $i goes from 1 to 9 and each time round the loop the variable $_ has a substitution applied to it.

    for (1..9) { s/\s/;/; }

    In this loop, you don't have $i so $_ is used as the iterator variable. So when you apply the substitution to $_ you are applying it to the numbers 1 to 9.

    I think that you were looking for this:

    for my $i (1..9) { s/\s/;/; }

    which does the same thing as your first loop.

    I have a nagging feeling that this may be an XY Question and that perhaps you should explain what you're really trying to do.

    --

    See the Copyright notice on my home node.

    "The first rule of Perl club is you do not talk about Perl club." -- Chip Salzenberg

Re: for loop syntax ...
by GrandFather (Saint) on Mar 21, 2007 at 10:28 UTC

    In the first case the loop iterates 9 times and the substitution operates on $_, which is not the loop variable because $i is supplied.

    In the second case the loop iterates 9 times and the substitutions operates on $_ which is the loop variable and takes the values 1 - 9 on successive passes through the loop (no loop variable supplied).

    The behaviour of the second form can be made the same as the first by providing a loop variable:

    for my $i (1..9) {s/\s/;/;}

    DWIM is Perl's answer to Gödel
Re: for loop syntax ...
by cilid (Initiate) on Mar 21, 2007 at 12:41 UTC
    Thank you, for providing me with the solution so quickly. To explain my self a little bit more… Some time ago I made a small Perl program for labeling my CD/DVDs and it was working well. I didn’t use the program for a few months, until couple days ago. But then program stopped working. I noticed that the problem was in the for loop syntax. The original line of code “for (1 .. 9) {s/\s/;/;}” didn’t work anymore. I replaced the syntax with “for (my $i = 1; $i <= 9; $i++) {s/\s/;/;}” and program started working again. To find that I lost half a day, because like I said, program worked before and I’m certain that I didn’t change anything in code. Except maybe I installed new version of Perl (Activestate) and some new Perl modules.

    So, thank you all for explaining me what’s the catch in “for (1 .. 9) …” syntax.

    Cilid