I am planning to use unpack in the file. First i tested with a string. When i have a embedded space in a string the below script is showing it as null. When i tested with a file space is getting read properly. Not sure why it’s changing it to null when i do with string. Can i use unpack while reading a fixed length file? Do i need to consider trailing space or anything else?
#!/usr/local/bin/perl
use strict;
use warnings;
my $str="hek kaaa";
print "<$str>\n";
foreach(unpack("(A1)*", $str)) {
print sprintf("%x", ord), " ";
}
Output:
<hek kaaa>
68 65 6b 0 6b 61 61 61
Thanks a lot for the response. Pasted my query below
When the perl program reads from a text file and unpacks using the format “A” is working properly. First line i have a embedded space in the first field between A and D. LABEL Variable gets printed as “A D3”. But when i had a variable $str=”A D3″ and unpacked the below way it’s having a null after A. How is it working differently when reading from a file and variable?
foreach(unpack("(A1)*", $str)) {
print sprintf("%x", ord), " ";
}
it displays as the hex output as
41 0 44 33
cat test.txt
A D37845566974923342XYZ24023984
QRW49327408234028434ERD24448009
my $file = 'test.txt';
open(my $data, '<', $file) or die "Could not open '$file'\n";
while (my $line = <$data>) {
print $line;
chomp $line;
my ($label, $source, $dest, $type, $value) = unpack ("A4 A8 A8 A4 A8", $line);
print "LABEL: $label SOURCE: $source DEST: $dest TYPE: $type VALUE: $value\n";
print "length of a string:" . length($line) . "\n";
foreach(unpack("(a1)*", $label)) {
print sprintf("%x", ord), " ";
}
print "\n";
}
This little nugget in the
pack/unpackdocumentation is easy to miss:As a workaround, you can use a
aorZin the template instead ofA: