WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Perl · Basic · question 17 of 100

What are Perl one-liners, and how can they be used for simple text processing tasks?

📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

Perl one-liners are short and concise command-line statements that use the Perl programming language to perform simple text processing tasks. These one-liners can be very handy when you need to perform repetitive tasks or need to quickly process data without writing a full-fledged Perl script.

Here is an example of a Perl one-liner that can be used to print out lines that match a certain pattern in a file:

perl -ne 'print if /pattern/' file.txt

Here, ‘-n‘ enables the automatic reading of each line from the input file one by one, and ‘-e‘ tells Perl that the next argument is the one-liner command to execute. The command ‘print if /pattern/‘ tells Perl to print any line that matches the pattern ‘/pattern/‘. You can replace ‘/pattern/‘ with any valid regular expression to match lines based on different criteria.

Another common task performed with one-liners is replacing patterns in a file. Consider this example:

perl -pi -e 's/oldword/newword/g' file.txt

This command uses the ‘-p‘ option to read the file line-by-line and print it back out with any changes made. The ‘-i‘ switch tells Perl to edit the file in place. The command ‘s/oldword/newword/g‘ replaces all occurrences of ‘oldword‘ with ‘newword‘ wherever it appears. You can use regular expressions and capture groups in the search and replace patterns to make more complex replacements.

One-liners can also be used to perform more complex tasks like counting words, filtering lines based on multiple criteria, joining files, and more. By combining various Perl commands in one-liners, you can create a powerful and flexible tool for text processing.

Overall, Perl one-liners are a powerful way to quickly perform simple text processing tasks on the command line without having to write a full script. With a little bit of practice and experimentation, you can become proficient at using Perl one-liners to automate your text processing tasks.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Perl interview — then scores it.
📞 Practice Perl — free 15 min
📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

All 100 Perl questions · All topics