Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Perl Split question - multiple search terms in one variable/pattern?

Status
Not open for further replies.

toddmanqa

Technical User
Aug 11, 2008
5
US
I'm trying to split text out that is contained between a set of brackets [].

I tried to place both variables inside the $split variable, but it would only recognize one of the brackets. I came up with this option, which works:

Code:
$line1 = 'before[within]after';

$split= ('\[');
$split2 = ('\]');

  @values = split(/$split|$split2/,$line1);	

  foreach $val (@values) {
    print "$val\n";
  };
and produces:

before
within
after

but I wanted to know if there is a way to combine the two bracket search terms into one variable.

thanks
 
It's probably easier not to do it with split:
Code:
$_ = 'before[within]after';
my @values = /^([^\[]+)\[([^\]]+)\](.+)/;
 
If you really need to use two scalars to store the split patterns:

Code:
$line1 = 'before[within]after';

$split= '[';
$split2 = ']';
@values = split(/[\Q$split$split2\E]/,$line1);    
foreach $val (@values) {
   print "$val\n";
};

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
To paraphrase Kevin:
Code:
@values = split(/[\[\]]/,$line1);
But beware that this will split 'before]within[after' in exactly the same way as 'before[within]after'(or 'before]within]after', ...)

_________________________________
In theory, there is no difference between theory and practice. In practice, there is. [attributed to Yogi Berra]
 
To make sure there is an opening bracket and it precedes the closing bracket:
Code:
$line1 = 'before [within]after';

$i1=index($line1,'[');
$i2=index($line1,']');

@values=($i1==-1 or $i2==-1)?$line1:
	($i1<$i2)?split(/[\[\]]/,$line1):$line1;

foreach $val (@values) {
   print "$val\n";
};
If the condition is not met, the line remains unsplit.

_________________________________
In theory, there is no difference between theory and practice. In practice, there is. [attributed to Yogi Berra]
 

you said
but I wanted to know if there is a way to combine the two bracket search terms into one variable.
do you mean something like the following?

Code:
$line = 'before[within]after';
$split= '\[|\]';
@values = split(/$split/,$line1);    
foreach $val (@values) {
  print "$val\n";
};


this will give 

before
within
after


``The wise man doesn't give the right answers,
he poses the right questions.''
TIMTOWTDI
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top