$id = 1; # <--- semicolon was missing open(MYFILE,"/var/tmp/mylist.dat") or die "Cant open mylist.dat" while (<MYFILE>) { # <--- wrong file handle fixed chomp; die "Request Id $id already present in file\n" if $_ eq $id; } close MYFILE;
$_, which gets assigned to by <MYFILE> in a while loop, is a scalar.
As such, it can hold a string or a number. The line is not magically split at the comma*. So, $_ just holds the entire line.
The operator eq compares its operands stringwise and returns true if both are equal. Perhaps you want to match?
die "Request Id $id already present in file\n" if /$id/;
The match operator m// is by default bound to $_; to match against something else you need the binding operator =~:
while (my $line = <MYFILE>) { chomp $line; die "Request Id $id already present in file\n" if $line =~ /$id/ +; }
If you really want an array and compare $id against its first element, you have to split the line into an array:
my @array = split /,/, $_; die "Request Id $id already present in file\n" if $array[0] eq $id +;
Note that split by default splits into the array @_ whose first element is $_[0] - but this usage is deprecated.
*) for magical split, look up the -a, -n, -p and -F switches, and the array @F in perlrun.
In reply to Re: Access elements of $_
by shmem
in thread Access elements of $_
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |