Question

I was playing with a solution for a question and I came up with this solution:

echo "hell-hello-helloo" | perl -e '@a=split(/\-/, <>);print join("-",@a[0,1]);'

It is just supposed to extract the first two tokens and remove the rest of the line.

My answer would have been cooler, more difficult to read and less maintainable if I could somehow move that first split inside the join and do it as one horrible piece of line noise.

I tried a few things, but I'm not sure how to do it. What I am trying to get to is something like this:

echo "hell-hello-helloo" | perl -e 'print join("-",@{split(/\-/,<>)}[0,1]);'
Was it helpful?

Solution

Using a perl oneliner

echo "hell-hello-helloo" | perl -F/-/ -ane 'print join("-",@F[0,1]);'

Or if you don't like the -F option to automate splitting, either of the below two:

echo "hell-hello-helloo" | perl -e 'print join "-", (split /-/, <>)[0,1]'
echo "hell-hello-helloo" | perl -pe '$_ = join "-", (split /-/)[0,1]'

OTHER TIPS

You can do this very concisely using a regular expression

echo "hell-hello-helloo" | perl -ne "print /([^-]+-[^-]+)/"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top