Return to Snippet

Revision: 47749
at June 15, 2011 19:11 by alwaysonnet


Updated Code
#!/usr/bin/perl

# subroutine to strip leading and trailing spaces
# in a string or an array.

# check for the examples below.

################################################################################
# trim()
#
#   Usage:
#       trim;                # trims $_ inplace
#       $new = trim;         # trims (and returns) a copy of $_
#       trim($str);          # trims $str inplace
#       $new = trim($str);   # trims (and returns) a copy of $str
#       trim(@list);         # trims @list inplace
#       @new = trim(@list);  # trims (and returns) a copy of @list
#################################################################################
sub trim {
    @_ = $_ if not @_ and defined wantarray;
    @_ = @_ if defined wantarray;

    for (@_ ? @_ : $_) { s/^\s+//, s/\s+$// }

    return wantarray ? @_ : $_[0] if defined wantarray;
}

Revision: 47748
at June 15, 2011 19:07 by alwaysonnet


Updated Code
#!/usr/bin/perl

# subroutine to strip leading and trailing spaces
# in a string or an array.

# check for the examples below.

################################################################################
# trim()
#
#   Usage:
#       trim;                # trims $_ inplace
#       $new = trim;         # trims (and returns) a copy of $_
#       trim($str);          # trims $str inplace
#       $new = trim($str);   # trims (and returns) a copy of $str
#       trim(@list);         # trims @list inplace
#       @new = trim(@list);  # trims (and returns) a copy of @list
#################################################################################
sub trim {
    my $self = shift;

    @_ = $_ if not @_ and defined wantarray;
    @_ = @_ if defined wantarray;

    for (@_ ? @_ : $_) { s/^\s+//, s/\s+$// }

    return wantarray ? @_ : $_[0] if defined wantarray;
}

Revision: 47747
at June 15, 2011 19:04 by alwaysonnet


Initial Code
################################################################################
# trim()
#
#   Usage:
#       trim;                # trims $_ inplace
#       $new = trim;         # trims (and returns) a copy of $_
#       trim($str);          # trims $str inplace
#       $new = trim($str);   # trims (and returns) a copy of $str
#       trim(@list);         # trims @list inplace
#       @new = trim(@list);  # trims (and returns) a copy of @list
#################################################################################
sub trim {
    my $self = shift;

    @_ = $_ if not @_ and defined wantarray;
    @_ = @_ if defined wantarray;

    for (@_ ? @_ : $_) { s/^\s+//, s/\s+$// }

    return wantarray ? @_ : $_[0] if defined wantarray;
}

Initial URL


Initial Description


Initial Title
strip leading and trailing spaces

Initial Tags


Initial Language
Perl