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

I need to figure out a way to arrange these two lines of code into one line.
It doesn't matter how its done as long as its in one line.

$string = "hello";
$string =~ /^\s+|\s$/g;

Replies are listed 'Best First'.
Re: need to consolidate two lines to one
by moritz (Cardinal) on Oct 23, 2008 at 19:40 UTC
    Perl is a free-form language, so you can actually write them on one line (although I don't see any sense in it):
    $string = "hello"; $string =~ /^\s+|\s$/g;

    Also since "hello" is a literal that contains neither leading nor trailing whitespaces, you can actually just write that as

    $string = "hello";
    If you have the string in a variable, you can write:
    ($string = $source) =~ s/^\s+|\s$/g;
Re: need to consolidate two lines to one
by gone2015 (Deacon) on Oct 23, 2008 at 19:41 UTC
    $string = "hello"; $string =~ /^\s+|\s$/g;

    It's a lot easier than it's made out to be this programming lark.

Re: need to consolidate two lines to one
by JavaFan (Canon) on Oct 23, 2008 at 20:10 UTC
    Considering that the second line doesn't match, and hence you don't even get any side effects, the simplest way to turn this into a one liner is to eliminate the second line.
Re: need to consolidate two lines to one
by ikegami (Patriarch) on Oct 23, 2008 at 20:37 UTC
    That code makes no sense. Did you mean s/^\s+|\s$//g;? If so,
    • my $string = EXPR; $string =~ s/^\s+|\s$//g;
    • (my $string = EXPR) =~ s/^\s+|\s$//g;
    • sub trim { my ($s) = @_; $s =~ s/^\s+|\s$//g; return $s; } my $string = trim( EXPR );
    • s/^\s+|\s$//g for my $string = EXPR;
    • my ($string) = map { my $s = $_; $s =~ s/^\s+|\s$//g; $s } EXPR;
    • use List::MoreUtils qw( apply ); my $string = apply { s/^\s+|\s$//g } EXPR;
    • use Algorithm::Loops qw( Filter ); my $string = Filter { s/^\s+|\s$//g } EXPR;
Re: need to consolidate two lines to one
by GrandFather (Saint) on Oct 23, 2008 at 19:48 UTC

    Why? Homework assignment?

    Ponder () used to control order of evaluation and what an assignment expression returns.


    Perl reduces RSI - it saves typing
Re: need to consolidate two lines to one
by trwww (Priest) on Oct 24, 2008 at 03:10 UTC
    (my $string = 'hello') =~ /^\s+|\s$/g;

    EDIT:

    Err, I guess that doesn't really do much... I think this does what you want:

    (my $foo = '  doo de doo  ') =~ s/^\s+(.+?)\s+$/$1/;

    EDIT 2:

    I think this more closely matches what you are looking for:

    (my $foo = '  doo de doo  ') =~ s/^\s+|\s+$//g;