19:50 <@Petruchio> Right now I'm inclined to code up a subroutine to overload chomp, so that it'll chomp every scalar value it finds recursively throughout a nested data structure.

I could not refrain myself from coding it immediately, so here it is :)

Update (200112202209+0100) It _does_ work, and doesn't use the outer $_. The line containing "#### <<< :-)" explains why. (for-modifier). merlyn was right about this not being easy to maintain. Sorry about that, let's just hope it doesn't need maintenance, then.

Update (200112211546+0100) gbarr uses defined() in his not-recursive version. I should have done so too, so I fixed that mistake. Also made it work with references to references.

sub mychomp; # Needed so mychomp can be used without parens # from within mychomp sub mychomp { ref eq 'ARRAY' ? do { mychomp $_ for @$_ } : ref eq 'HASH' ? do { mychomp $_ for values %$_ } : ref eq 'REF' ? do { mychomp $$_ } : ref eq 'SCALAR' ? eval { defined && chomp $$_ } : ref || defined && chomp for @_ #### <<< :-) } # Useful stuff ends here :) # Testing stuff starts here :) $foo = "scalar\n"; @foo = (["first\n", "second\n", "third\n"], [[ "FIRST\n", "SECOND\n", +"THIRD\n"], [{xyzzy => "1st\n"}],{ xyzzy => "1<sup>st</sup>\n"} ], "Just testing\n", \ $foo, \ \ \ $foo, \ [ "Testing :)\n" ], [[[[[[[[[[[[[[[[[ "DEEEEEPER!\n" ]]]]]]]]]]]]]]]]] ); mychomp @foo; use Data::Dumper; print Data::Dumper->Dump(\@foo); # oh, and $foo is chomped too, of course

In reply to chomp any data structure recursively by Juerd

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.