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

I am using the split method to split a string. I get an array and use a specific index to assign the value to a variable.
@temp_array3 = split("=", $line); $schema_username = $temp_array3[1];
Is there a way to directly assign the variable schema_username w/o using the temp_array3? Vijay.

Replies are listed 'Best First'.
Re: split and assign
by JadeNB (Chaplain) on Aug 03, 2009 at 04:25 UTC
    You can index directly into the result of a function call:
    $schema_username = ( split '=', $line )[1];

    Note also that the first argument to split is a regex, not a string literal, even if you mean it to be. In particular, split '.', EXPR probably won't behave as you expect.

    (In fact, split '\.', EXPR and split /\./, EXPR behave differently—I don't know why.
    Oh, now I see. What I actually tested was split "\.", EXPR, and Perl regards "\." as a (pointless) escaping of ., so that it's read the same as "."—which, when interpreted as a regex, matches any single character. In split '\.', EXPR, no escaping is done, so everything's fine.)

      And there's also:
      >perl -wMstrict -le "my $line = 'foo=bar=baz'; my (undef, $schema_username) = split /=/, $line; print $schema_username; " bar
      Update: Although it must be admitted that this approach would get a bit tedious if one were interested not in the second field but in the twenty-second!
        Although it must be admitted that this approach would get a bit tedious if one were interested not in the second field but in the twenty-second!
        I hoped for a mad moment that
        my ( ( undef ) x 21, $var ) = func;
        or at least
        ( ( undef ) x 21, my $var ) = func;
        would work—but they don't ….
      You can index directly into the result of a function call....

      You can make a list slice of any expression which evaluates to a list.

Re: split and assign
by Anonymous Monk on Aug 03, 2009 at 20:26 UTC
    my $schema_username = ( split /=/, $line )[1];

    or

    my ($schema_username) = $line =~ /=(.*)/s;

    By the way, the first arg of split is a regex. Don't fool yourself into thinking it matches literally by using quotes.

    - ikegami

Re: split and assign
by Anonymous Monk on Mar 04, 2014 at 18:42 UTC
    What about if I need 3 of the elements, not just one? Right now I'm using:
    $line = "aa;bb;cc;dd;ee"; my @stuff = split(/;/, $line); my $a = $stuff[0]; my $b = $stuff[1]; my $d = $stuff[3];
    Is there a shortcut to this?
    I'm actually parsing a csv and only need columns 1, 2 and 8... Thanks!
      I'm actually parsing a csv and only need columns 1, 2 and 8
      my ($a, $b, $c) = (split /;/, $line)[0,1,7];
        Thanks! My brain is fried, I kept trying multiple [] like [0][1][7] and [0],[1],[7]...