How to take substring of a given string until the

2019-04-23 05:26发布

问题:

The question if for perl.

For example if I have "hello.world" and the specified character is '.' then the result I want is "hello".

回答1:

See perldoc -f index:

$x = "hello.world";
$y = substr($x, 0, index($x, '.'));


回答2:

Using substr:

my $string = "hello.world";
my $substring = substr($string, 0, index($string, "."));

Or using regexp:

my ($substring2) = $string =~ /(.*)?\./;


回答3:

use strict;
use warnings;

my $string = "hello.world";
my $dot = index($string, '.');
my $word = substr($string, 0, $dot);

print "$word\n";

gives you hello



回答4:

Another possibility:

my $string = 'hello.world';
print ((split /\./, $string)[0], "\n");


回答5:

In the spirit of TIMTOWTDI, and introducing new features: Using the non-destructive option /r

my $partial = $string =~ s/\..*//sr;

The greedy .* end will chop off everything after the first period, including possible newline characters (/s option), but keep the original string intact and remove the need for parens to impose list context (/r option).

Quote from perlop:

If the /r (non-destructive) option is used then it runs the substitution on a copy of the string and instead of returning the number of substitutions, it returns the copy whether or not a substitution occurred. The original string is never changed when /r is used. The copy will always be a plain string, even if the input is an object or a tied variable.