dgBP
dgBP

Reputation: 1691

How do I truncate a string from a specific character in perl?

I have a string 'Basingstoke & Deane' and I would like to check for the '&' symbol and cut the string from (and including) that point.

So my input would be: 'Basingstoke & Deane'

And the output would be: 'Basingstoke '

I can search for the '&' fine using $string =~ /&/ and can replace/delete it using s/&//, but I'm having a mental block of how to delete & and all characters after it. The extra space left over does not matter.

This is one of many strings, so thus a generic solution would be best. Apologies if this has been asked before, I've seen a lot of questions about truncating a string using substr and questions searching for a specific string and so on, but nothing quite what I'm looking for. Any help appreciated.

Upvotes: 0

Views: 1420

Answers (3)

ikegami
ikegami

Reputation: 385917

my ($prefix) = $string =~ /^([^&]*)/s;

my ($prefix) = split /&/, $string;      # Slightly faster, IIRC

In-place:

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

Upvotes: 2

Hunter McMillen
Hunter McMillen

Reputation: 61510

You could also find the index of the & and use the substr function to take a portion of the string:

my $string    = 'Basingstoke & Deane';
my $amp_index = index($string, '&');

print substr($string, 0, $amp_index);
# Basingstoke 

Courtesy of @TLP (substr as an lvalue):

substr($string, index($string, '&')) = ""

Upvotes: 2

TLP
TLP

Reputation: 67918

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

Will delete the rest of the string, including newlines.

Upvotes: 5

Related Questions