Below is the script, i feel there should be more simple way to do the same output, my one works, but feel not nice. like using index i feel it is slow (image my file is very large), maybe awk can do one line code?
Please advice.
[root@tmp]# cat 1.txt
1 a
2 b
3 cc
4 d
[root@tmp]# cat 1.pl
#!/usr/bin/perl
use strict;
use warnings;
my $str="a,cc";
open(my $FA, "1.txt") or die "$!";
while(<$FA>) {
my @tmp=split;
chomp;
if (index($str, $tmp[1]) ne -1) {
print "@tmp\n";
}
}
[root@tmp]# ./1.pl
1 a
3 cc
[root@tmp]#
---------- Post updated at 02:16 AM ---------- Previous update was at 02:05 AM ----------
Hi Pludi,
I tried below, if i use the perl code put into one pl file, how to do that, because below shows error:
[root@tmp]# cat 1.pl
#!/usr/bin/perl
use strict;
use warnings;
print if $F[1]=~/a|cc/ "1.txt";
[root@tmp]# ./1.pl
String found where operator expected at ./1.pl line 5, near "/a|cc/ "1.txt""
(Missing operator before "1.txt"?)
Global symbol "@F" requires explicit package name at ./1.pl line 5.
syntax error at ./1.pl line 5, near "/a|cc/ "1.txt""
Execution of ./1.pl aborted due to compilation errors.
[root@tmp]# perl -ane 'print if $F[1]=~/a|cc/' 1.txt
1 a
3 cc
how to involve this perl -ane '......' 1.txt into the pl file.
Ah, I thought you were looking for a 1-liner. Complete, stand-alone script:
#!/usr/bin/perl
use strict;
use warnings;
use Carp;
open my $FH, '<', '1.txt' or croak "Can't open 1.txt: $!";
print grep { local @_ = split; $_[1] =~ /a|cc/ } <$FH>;
close $FH;
Yes, usually they are. But the second form will upset the Perl debugger should you ever need it, while the former won't. Also, in extreme cases the warnings pragma can be disabled for short blocks, while the switch can't (to the best of my knowledge).