Is there a one-liner to get the first element of a split?

前端 未结 3 393
梦如初夏
梦如初夏 2021-01-01 09:54

Instead of writing:

@holder = split /\\./,\"hello.world\"; 
print @holder[0];

is it possible to just do a one-liner to just get the first e

3条回答
  •  一整个雨季
    2021-01-01 10:25

    You should have tried your hunch. That’s how to do it.

    my $first = (split /\./, "hello.world")[0];
    

    You could use a list-context assignment that grabs the first field only.

    my($first) = split /\./, "hello.world";
    

    To print it, use

    print +(split /\./, "hello.world")[0], "\n";
    

    or

    print ((split(/\./, "hello.world"))[0], "\n");
    

    The plus sign is there because of a syntactic ambiguity. It signals that everything following are arguments to print. The perlfunc documentation on print explains.

    Be careful not to follow the print keyword with a left parenthesis unless you want the corresponding right parenthesis to terminate the arguments to the print; put parentheses around all arguments (or interpose a +, but that doesn't look as good).

    In the case above, I find the case with + much easier to write and read. YMMV.

提交回复
热议问题