Perl - use search keywords from array and search a file and print 3rd field when matched

Hi ,

I have been trying to write a perl script to do this job. But i am not able to achieve the desired result. Below is my code.

my $current_value=12345;
my @users=("bob","ben","tom","harry");
open DBLIST,"<","/var/tmp/DBinfo";
my @input = <DBLIST>;

foreach (@users)
{
my $req_user_info=grep(/$_/,@input);
my ($user,$blah,$value)=split(/:/,$req_user_info);
my $diff=$current_value-$value;
print "$diff";
}}

Can some please help me understand what i am missing and how to edit this code to get the desired result.

Hi

It would have been better had your provided a sample input file of yours. At hindsight, this is one issue:

foreach  my $x (@users)
{
my $req_user_info=grep(/$x/,@input);
my ($user,$blah,$value)=split(/:/,$req_user_info);
my $diff=$current_value-$value;
print "$diff";
}

Guru.

@ Guru , i am using perl default variable $_ . Hence i have not used a separate variable in foreach loop.

@chidori : Did you try the above solution? I understand you tried to use $, but it should not be used when using grep. This is because grep internally uses $ to process each element of the array.

Guru.

i can see

my $req_user_info=grep(/$x/,@input);

the output of grep looks like "0" and "1" so the variable $req_user_info is holding numbers. but i would require something like search for the pattern and when match is found store that line in variable

Hi
You should use it like this:

my ($req_user_info)=grep(/$x/,@input);

This is because grep returns a list, and when used in scalar context, you get the length.

Guru.

1 Like

Thanks Guru.. It worked :slight_smile:

Looking at your code, it makes sense to use the first subroutine from the List::Util core module, instead of grep . With that, you may not use the set of parentheses.

Hi Elixr ,

Thanks for the suggestion. I am a beginner in perl :slight_smile: so i am trying with what i have learnt. Will have check on that module. Also i dont like one part of my code

my ($user,$blah,$value)=split(/:/,$req_user_info);

if you see this. all i want is $value that is present in 3rd column. Well since split will start spliting from the start ( thats my understanding) i have to use 2 extra variables which i like to avoid. Any suggestions in doing that ?

$value=(split(/:/,$req_user_info))[3];
1 Like

Thanks binlib.. it worked. btw.. does that mean we can use split function as a array ?

That technique is called list slicing. Also, read about array slices.