How to take substring of a given string until the

2019-04-23 04:44发布

The question if for perl.

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

5条回答
Emotional °昔
2楼-- · 2019-04-23 05:18

Using substr:

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

Or using regexp:

my ($substring2) = $string =~ /(.*)?\./;
查看更多
Anthone
3楼-- · 2019-04-23 05:25

Another possibility:

my $string = 'hello.world';
print ((split /\./, $string)[0], "\n");
查看更多
不美不萌又怎样
4楼-- · 2019-04-23 05:26

See perldoc -f index:

$x = "hello.world";
$y = substr($x, 0, index($x, '.'));
查看更多
爷的心禁止访问
5楼-- · 2019-04-23 05:37
use strict;
use warnings;

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

print "$word\n";

gives you hello

查看更多
smile是对你的礼貌
6楼-- · 2019-04-23 05:39

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.

查看更多
登录 后发表回答