Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re^2: Substring comparison

by schtinkfist893 (Novice)
on May 01, 2012 at 16:25 UTC ( [id://968297]=note: print w/replies, xml ) Need Help??


in reply to Re: Substring comparison
in thread Substring comparison

Excellent! flaviodesousa solution works for explicitly defined arrays

my @Array1 = qw{XXX FFF ZZZ AAA BBB QQQ LLL JKK III CCC DDD DCD};
my @Array2 = ("XXX BBB AAA CCC DDD EEE", "FFF NNN JKK III LLL QQQ");

XXX IS found in XXX BBB AAA CCC DDD EEE
XXX IS NOT found in FFF NNN JKK III LLL QQQ
FFF IS NOT found in XXX BBB AAA CCC DDD EEE
FFF IS found in FFF NNN JKK III LLL QQQ

However my arrays are being read in from a text file
my $file1 = '/tmp/file1.txt'; my @Array1; open FILE, $file1 or die $!; while(<FILE>) { @Array1 = <FILE>; } my $file2 = '/tmp/file2.txt'; my @Array2; open FILE, $file2 or die$!; while(<FILE>) { @Array2 = <FILE>; } print @Array1; Print @Array2;
/tmp/file1.txt is as stated above
XXX FFF ZZZ AAA BBB QQQ LLL JKK III CCC DDD DCD

/tmp/file2.txt is
XXX BBB AAA CCC DDD EEE FFF NNN JKK III LLL QQQ

This outputs
FFF ZZZ AAA BBB QQQ LLL JKK III CCC DDD DCD FFF NNN JKK III LLL QQQ

So it looks the method I am reading in the Arrays is not as thorough as I expect it to be.

Replies are listed 'Best First'.
Re^3: Substring comparison
by johngg (Canon) on May 01, 2012 at 21:31 UTC
    while(<FILE>) { @Array1 = <FILE>; }

    That is not going to do quite what you'd hoped. The first time into the loop it will read the first line of the file into the $_ variable, which you never use so that line will be lost. Then, inside the loop you read the file handle in list context as you have an array on the LHS. That will have the effect of reading the remaining lines of the file, one line per element, into the array; the the loop will exit on the next iteration as EOF has been reached. Your array will contain all lines but the first. As you've discovered in your subsequent post you will have to chomp to get rid of line terminators. The correct way to populate your array in a loop would be to use push.

    my @arr; while ( <$fh> ) { chomp; push @arr, $_; }

    However, there is an easier way as chomp will also operate on arrays

    my @arr = <$fh>; chomp @arr;

    or even

    chomp( my @arr = <$fh> );

    I hope this is helpful.

    Cheers,

    JohnGG

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://968297]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2024-04-16 09:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found