How can I suppress empty leading fields in Perl split ()?

perlfunc for split says:

By default, empty start fields are saved.

Assuming there is a way to convince this default value, but later all he says is:

Empty start fields are created when at the beginning of a line

there are matches with a positive width.

... does this mean that there is no way to skip this first field?

This is not critical, but I split the root URL into, say /foo/bar/, slashes and getting

['', 'foo', 'bar']

and wonders if there is a way to not get this empty first element.

+3
source share
7 answers

, File:: Spec Path:: Class, :

 use File::Spec;

 my( $root, @path_parts ) = File::Spec->splitdir( $path );

, , , - ( ):

 my $path = File::Spec->catfile( $root, @path_parts );

URL-, unix. , , ( Windows, VMS ..):

 my ($docroot_root, @doc_root ) = File::Spec->splitdir( $ENV{DOCUMENT_ROOT} );
 my $local_path = File::Spec->catfile( $docroot_root, @doc_root, @path_parts );

, . , , (.. 0 , ). , , , ,

 my( $root, @path_parts ) = split m|/|, $path;
+7

grep .

grep (length, split ('/','/foo/bar'))

, , .

, , , , . , , .

+6

brian d foy File::Spec. , , , .

/ Perl :

($volume, $directories, $file) = File::Spec->splitpath( $path );

, , , !

! , , , , .

+1

"/", , . , , , .

-1

, , - .

.

$str = "/foo/bar";
$str =~ m!^/*!!;

Then make your split as before.

-1
source

split(' ', $string) will split the string into spaces, but will not give you start, end or internal empty fields.

I thought this was a more general case, but dividing by is 'x'equivalent/x/

-1
source

like this

(undef,@x)= split /\//,$string;
-1
source

Source: https://habr.com/ru/post/1718668/


All Articles