What's wrong

A

Alex

Here is my perl script:

my %files;
my $filepath = "test.txt";
open (IN, $filepath);
while (<IN>) {
chomp;
my $file = $_;
$files{$file} = $file;
}
close IN;

my $code = 10;
if (exists $files{$code}) {
print "find key\n";
}
exit;

here is test.txt file:
10
20
30

When I run the script, there is no print "find key". However, if I change
the scipt to:


my %files;
my $filepath = "test.txt";
open (IN, $filepath);
while (<IN>) {
chomp;
my $file = substr($_,0,2);
$files{$file} = $file;
}
close IN;

my $code = 10;
if (exists $files{$code}) {
print "find key\n";
}
exit;

It will print "find key". I could find out what's wrong. Why change

my $file = $_;
to
my $file = substr($_,0,2);

will work.

PS: in test.txt file, after type 10 followed by Enter key.

Thanks in advance!
 
G

Gunnar Hjalmarsson

Alex said:
Here is my perl script:

my %files;
my $filepath = "test.txt";
open (IN, $filepath);
while (<IN>) {
chomp;
my $file = $_;
$files{$file} = $file;
}
close IN;

my $code = 10;
if (exists $files{$code}) {
print "find key\n";
}
exit;

here is test.txt file:
10
20
30

When I run the script, there is no print "find key".

A wild guess: test.txt contains Windows newlines ( \015\012 ), while the
script is run on *nix ( \012 ).
 
J

Joe Smith

Alex said:
Why change
my $file = $_;
to
my $file = substr($_,0,2);
will work.

You should get perl to print out what it is actually working with.
Change
chomp;
to
print "Before: ",(unpack "H*",$_),"\n";
chomp;
print "After: ",(unpack "H*",$_),"\n";
to see if there are more than two characters on the line after chomp().

-Joe
 
D

Dr.Ruud

Joe Smith schreef:
print "Before: ",(unpack "H*",$_),"\n";

To get the bytes separated, one can do

{ local ($\, $,) = ("\n", '.') ;
print "Before: ", unpack('(H2)*', $_) ;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top