Why not go ahead and Make A Better Chomp(tm)? Here's my first stab at it; it basically follows the rules of:
- Currently just strips all trailing white space
- If passed a reference, operate on it directly (duh! But also works for passing arrays of references) and return a dud value
- Otherwise return the modified string(s) without touching the originals.
- 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)
- 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;
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|