Reputation: 195
I have a line which looks like this:
(ABCD)(ABCDE)(ABCDEF)(ABCDEFG)
but I want to store it like this :
ABCDABCDEABCDEFABCDEFG
in a variable called parser. The code I am using is
my ($parser) = $subckt =~ m/\s*(\(.*?)\);
Here $subckt
variable stores the actual line with brackets.
How do I get the required data in the variable $parser
.
Please help.
Thanks
Upvotes: 0
Views: 3582
Reputation: 124646
If you simply want to remove the parentheses as the title suggests,
the substitution operator s///
is the natural choice:
my $subckt = '(ABCD)(ABCDE)(ABCDEF)(ABCDEFG)';
my $parser = $subckt;
$parser =~ s/[()]//g;
That said, it's a bit hard to guess what you really want to do and what kind of possible inputs you have.
Based on the broken regex in the post, perhaps what you really want is change patterns of \s*\(X\)
to X
. If that's the case, then instead of a substitution, it will be easier to use a matching, with a capture group, similar to the way you seem to have tried:
my $subckt = '(ABCD)(ABCDE)(ABCDEF)(ABCDEFG)';
my ($parser) = join('', $subckt =~ m/\s*\((.*?)\)/g);
This will also work with input like this:
my $subckt = ' (ABCD) (ABCDE)(ABCDEF)(ABCDEFG)';
The way this works:
m/...(...).../g
returns a list of the matched strings captured within (...)
(
and )
, so the expression should in fact look like m/...\((...)\).../g
, notice the \(
and \)
outside of the (...)
capture/g
flag is important (was missing in yours), otherwise pattern matching will stop after the first matchUpvotes: 1
Reputation: 126722
The translate operator tr
is what you need. With the /d
(delete) modifier you can delete all characters in the list that have no corresponding replacement.
If you have version 14 or later of Perl 5 then the /r
(non-destructive) modifier makes it a lot tidier.
This program demonstrates
use 5.014;
my $subckt = '(ABCD)(ABCDE)(ABCDEF)(ABCDEFG)';
my $parser = $subckt =~ tr/()//dr;
print $parser;
output
ABCDABCDEABCDEFABCDEFG
Upvotes: 2
Reputation: 35198
Initialize your new variable, and then remove all non-word characters
( my $parser = $subckt ) =~ s/\W//g;
Or using the /r
Modifier:
my $parser = $subckt =~ s/\W//gr;
Upvotes: 1
Reputation: 515
Try replacing all occuences of bracket, which the g flag does
$subckt =~ s/\(//g;
$subckt =~ s/\)//g;
Upvotes: 0