Perl: removing rest of the string after encountering a certain character

34,792

Solution 1

Quickest is by an easy regular expression:

$string =~ s/\$.*//;

where

$string = 'abc$hello-goodbye';

Solution 2

You could either use regex or a combination of index and substr.

This shouldn't be too difficult.

Solution 3

In Ruby,

>> "abc$def".split("$")[0]
=> "abc"
>>

Similarly, use the split() function from Perl to do this and get the first element. See perldoc -f split for more information

Share:
34,792
sfactor
Author by

sfactor

Dreamer, Analyst, Engineer, Programmer, Photographer.

Updated on April 08, 2020

Comments

  • sfactor
    sfactor about 4 years

    I am doing some clean up of data in a file. So, I read each line and check certain conditions and perform the appropriate operation in the file. One of the things I need to do is check for the occurrence of the character $ in the string. If found I need to delete the rest of the line including the $. Example, if the line is

    abc$hello-goodbye
    

    I need to get

    abc
    

    How do I do this in Perl with minimal code? Use regexp of some sort?