I’m trying to find two patterns within an array and put the results into another array.
For example
$/ = "__Data__";
__Data__
#SCSI_test # put this line into @arrayNewLines
kdkdkdkdkdkdkdkd
dkdkdkdkdkdkdkdkd
- ccccccccccccccc # put this line into @arrayNewLines
Code
while(<FILEREAD>)
{
chomp;
my @arrayOld = split(\n,@array);
foreach my $i (0 .. $#arrayOld)
{
if($arrayOld[$i] =~ /^-(.*)/g or /\#(.*)/g)
{
my @arrayNewLines = $arrayOld[$i];
print "@arrayNewLines\n";
}
}
}
This code only prints out only ccccccccccccccc
But I would like it to output ccccccccccccccc #SCSI_test
That code does not print just
cccccc..., it prints everything. Your problem is this line:What you are doing here is first checking
$arrayOld[$i]and then checking$_, because/\#(.*)/is perl shorthand for$_ =~ /\#(.*)/. Since the line contains a hash character#, it will always match, and the line will always print.Your line is equivalent to:
The answer there is to join the regexes:
However, your code is far from clean after that… starting from the top:
If you set the input record separator
$/to__Data__with that input, you will get two records (Data::Dumper output shown below):When you
chompthe records, you will remove__Data__from the end, so the first line will become empty. So in essence, you will always have a leading empty field. This is nothing horrible, but something to remember.Your
splitstatement is wrong. First off, the first argument should be a regex:/\n/. The second argument should be a scalar, not an array.split(/\n/,@array)will evaluate tosplit(/\n/, 2), because the array is in scalar context and returns its size instead of its elements.Also, of course, since you are in a loop reading lines from the
FILEREADhandle, that@arrayarray will always contain the same data, and has nothing to do with the data from the file handle. What you want is:split /\n/, $_.This loop:
is not a very good loop structure for this problem. Also, there is no need to use an intermediate array. Just use:
When you do
You are setting the entire array to a scalar, then printing it, which is completely redundant. You get the same effect just printing the scalar directly.
Your code should look like this:
It is also recommended that you use lexical file handles, so instead of
use: