tags:

views:

94

answers:

4

I have a string like this <name>, I want to chop off the <> and take out only name and put it into a variable.

How to do it using perl "split" function?

A: 

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
mfontani
Why not `split( /[<>]/, $str )`?
Dummy00001
A: 

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

Martin
Why the `,` in regexp?
Dummy00001
'cause I'm an idiot! Corrected - thanks.
Martin
+1  A: 

You can use regex and matching in list context:

my $s = "<name>";
my ($name) = $s =~ /<(.*)>/;
eugene y
This method is very useful it works perfectly...Thanks buddy ..i used " /<(\S*)>/ " ...
Senthil kumar
You probably want the non-greedy quantifier on that *, just in case.
brian d foy
Or use `/<([^>]*)>/` to make it explicit (both to `perl` and to future readers of your code) that you're looking for *non-'>'* characters rather than *any character at all* (which is what `.` means in a regex).
Dave Sherohman
+6  A: 

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;
brian d foy