Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Chomping Away (was Ovid Golf Chomps)

by mr.nick (Chaplain)
on Jan 09, 2001 at 08:19 UTC ( #50624=note: print w/ replies, xml ) Need Help??


in reply to (Ovid -Golf) Re(3): How do you chomp your chomps?
in thread How do you chomp your chomps?

Why not go ahead and Make A Better Chomp(tm)? Here's my first stab at it; it basically follows the rules of:

  1. Currently just strips all trailing white space
  2. If passed a reference, operate on it directly (duh! But also works for passing arrays of references) and return a dud value
  3. Otherwise return the modified string(s) without touching the originals.
  4. Works on scalar, arrays and hashes (why not? :) It modifes the values, not the keys, though it would be no problem to add that, too)
  5. Recursive (didn't a just read something here about "real" uses of recursion?) so you can use wacky data structures.

I didn't put a lot of brainpower into this; just wanted to share a thought of improvement. Enjoy!

sub mchomp { my @a=@_; local $_; foreach (@a) { if (ref $_ eq 'SCALAR') { $$_=~s/\s+$//; } elsif (ref $_ eq 'ARRAY') { @$_=mchomp(@$_); } elsif (ref $_ eq 'HASH') { for my $k (keys %$_) { $_->{$k}=mchomp($_->{$k}); } } else { s/\s+$//; } } wantarray ? @a: $a[0]; }

Examples

## returns the modified string print mchomp $string; ## modifies the variable directly mchomp \$string; print $string; ## returns an array of modified strings print join ",",mchomp @array; ## modifes the array inplace mchomp \@array; print join ",",@array; ## returns the modified hash %new=mchomp %hash;print values %new; ## modifes the hash inplace mchomp \%hash;print values %hash;


Comment on Re: Chomping Away (was Ovid Golf Chomps)
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://50624]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2015-07-04 11:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (59 votes), past polls