How to remove specific characters from an array elements in one line using Perl?
Example:-
In this array, the special character '
has to be removed.
@names = ("'Tom'","'Jerry'");
Expected Output :-
Tom
Jerry
The string literal 'Tom'
produces the string Tom
, and the string literal 'Jerry'
produces the string Jerry
, so there is no '
in any of the elements of that array.
To print each element on a different line, you can use the following:
say for @names;
It a short version of the following:
for my $name (@names) {
say $name;
}
This usually goes without saying, but using say
requires using use feature qw( say );
.
You can make this change in perl by negating the "specialness" of the character by placing a slash in front of it in the regex. So the regex for the variable could be s/\'//g
. An example could be as follows:
#!/usr/bin/perl
@names=('\'Tom\'','\'Jerry\'');
foreach my $name (@names) {
print "Name is $name\n";
$name =~ s/\'//g;
print "After regex, Name is $name\n";
}
In your array declaration with the single quotes though, perl will interpret those as simple quoting your inputs and will not include them in the output. I needed to add the negation of the single quote to produce the results which are:
Name is 'Tom'
After regex, Name is Tom
Name is 'Jerry'
After regex, Name is Jerry
$name =~ s/'//g
will work fine.
Commented
Mar 11, 2019 at 9:02
The code and your question is different. But looking at the Output you want i will assume that you want to join/print the elements of the array. Consider the example code:
Code:
@names = ('Tom','Jerry');
my $str = join '\n', @names;
say $str;
Output:
Tom
Jerry
'
in your code you can use@names = qw(Tom Jerry);
but the result will be the same@names = ("'Tom'", "'Jerry'")
or@names = qw('Tom', 'Jerry')
. Your code doesn't put quotes in the array elements.