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

I want to print a reversed array from STDIN,
This works:
#---------------------------------- #Pass @temp=<STDIN>; chomp(@temp); @new1=reverse(@temp); foreach $new(@new1) { $new = "\t$new"; print $new."\n"; } #----------------------------------

But why this doesen't:
#---------------------------------- @getnew=reverse(chomp(@temp=<STDIN>)); foreach $new(@getnew) { $new = "\t$new"; print $new."\n"; }

Thank you.

Replies are listed 'Best First'.
Re: basic question:how to print a reversed array from STDIN
by ikegami (Patriarch) on Dec 04, 2008 at 10:23 UTC

    Because chomp "returns the total number of characters removed from all its arguments."

Re: basic question:how to print a reversed array from STDIN
by ccn (Vicar) on Dec 04, 2008 at 11:09 UTC

    You also may try the following funny onliner script

    perl -pe '$\=$_.$\}{'

    Yes, it prints reversed array of lines from STDIN

Re: basic question:how to print a reversed array from STDIN
by holli (Abbot) on Dec 04, 2008 at 12:25 UTC
    The reason why is what ikegami said. So try this:
    @getnew=reverse(map { chomp; $_} <STDIN>);
    or
    chomp(@temp=<STDIN>); @getnew=reverse(@temp);
    Whatever you like best. I prefer the first version.


    holli, /regexed monk/
      I think this is neater:
      chomp(@getnew = reverse <STDIN>);
      I cringe when I see map or grep modify $_.
        I agree with you in regards to grep, but map? It's sole purpose is the modification of $_.


        holli, /regexed monk/
Re: basic question:how to print a reversed array from STDIN
by poolpi (Hermit) on Dec 04, 2008 at 14:14 UTC
      Three bugs:
      • It doesn't print the last character of the input if the line has no line ending.
      • It doesn't print a trailingleading zero.
      • It's a poor way of achieving the goal.

        Dear ikegami,

        I had never have the intention to submit this little piece of code to Perl 6 core modules...

        For me, it was just a funny variation on chomp.

        To be constructive, please give some examples because i can't reproduce two of your three remarks

        Laziness, impatience, hubris and why not humility.

        hth,
        PooLpi

        'Ebry haffa hoe hab im tik a bush'. Jamaican proverb