How to take a substring of a given string before the first occurrence of the specified character?

Question to Perl.

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

+8
source share
5 answers

See perldoc -f index :

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

Using substr :

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

Or using regex:

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

In the spirit of TIMTOWTDI and the introduction of new features: using the non-destructive variant /r

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

The greedy end .* Cuts off everything after the first period, including possible newline characters (option /s ), but keeps the original line intact and eliminates the need for overlaying the list context ( /r )).

Quote from perlop:

If the / r (non-destructive) parameter is used, it starts the replacement with a copy of the string and instead of returning the number of substitutions, it returns a copy, regardless of whether the replacement occurred. The original string never changes when / r is used. The copy will always be a simple string, even if the input is an object or a related variable.

+2
source
 use strict; use warnings; my $string = "hello.world"; my $dot = index($string, '.'); my $word = substr($string, 0, $dot); print "$word\n"; 

gives you hello

+1
source

Another possibility:

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

All Articles