开发者

Splitting a string to remove surrounding < and > characters

开发者 https://www.devze.com 2023-01-12 07:39 出处:网络
I have a string like this <name>, I want to chop off the <> and take out onlyname a开发者_Go百科nd put it into a variable.

I have a string like this <name>, I want to chop off the <> and take out only name a开发者_Go百科nd put it into a variable.

How to do it using perl "split" function?


Don't use split. That's like using the wrong end of a screwdriver to hammer in nails. I'd do it in some step with a match where you capture the part that you want in list context:

 my( $var ) = $input =~ /<(.*?)>/;

Alternatively, you could just remove the brackets with one of these:

 $input =~ tr/<>//;
 $input =~ s/[<>]//g;


You can use regex and matching in list context:

my $s = "<name>";
my ($name) = $s =~ /<(.*)>/;


In answer to you question about how to do it using split then you can do this:

$input ="<string>";
print split(/[<>]/,$input);

Click for live example

A better method however would be

$input = "<string>";
print $input =~ /<(.*)>/;

Click for live example


I'm not too sure why you'd want to use split for that... but here it goes:

> perl -le'$str="<string>";print split("<",(split(">",$str))[0]);'
string
0

精彩评论

暂无评论...
验证码 换一张
取 消