The question if for perl.
For example if I have "hello.world"
and the specified character is '.'
then the result I want is "hello"
.
The question if for perl.
For example if I have "hello.world"
and the specified character is '.'
then the result I want is "hello"
.
See perldoc -f index
:
$x = "hello.world";
$y = substr($x, 0, index($x, '.'));
Using substr
:
my $string = "hello.world";
my $substring = substr($string, 0, index($string, "."));
Or using regexp:
my ($substring2) = $string =~ /(.*)?\./;
use strict;
use warnings;
my $string = "hello.world";
my $dot = index($string, '.');
my $word = substr($string, 0, $dot);
print "$word\n";
gives you hello
Another possibility:
my $string = 'hello.world';
print ((split /\./, $string)[0], "\n");
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.