Walt Mankowski via plug on 14 Oct 2024 17:01:15 -0700 |
[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]
Re: [PLUG] Simple Perl question |
Hi Eric, I'm not 100% sure I'm following your logic, but it looks like you're trying to treat $output as a string where you're appending one binary digit at a time. If that's the case, then try changing `+=` to `.=` so you're appending instead of adding. That said, I think you're going about it the wrong way. Perl's pack() function will convert integers to binary for you without doing all this work. Here's an example: #!/usr/bin/env perl my $output = 0; while (<<>>) { chomp; my @nums = split ','; for my $num (@nums) { $output *= 2; $output += 1 if $num; } printf STDERR "%b\n", $output; print pack ("i", $output); } ---- Sample run: % perl cvs2bin.pl input.csv | xxd -b 110101 00000000: 00110101 00000000 00000000 00000000 5... Hope this helps! Walt On Mon, Oct 14, 2024 at 07:17:35PM -0400, Eric Lucas via plug wrote: > I'm trying to quickly put together a little utility in perl to help me with > a task. > > The object is to take a csv file containing a row of either 0, 1, or , and > write it out as a binary file that matches the csv input. > > Here's the code: > > #! /usr/bin/perl > my @line; > my $char; > my $output; > my $binOut = 1; > > my $file = shift @ARGV or die "ERROR: You gotta give me a file name!\n"; > > open $FILE, '<', $file or die "BAH!\n" ; > > while (@line = split(//,<$FILE>)) { > my $count = @line; > for (my $x=0; $x<$count; $x++) { > if ($line[$x] =~ /1/) { > print "one " if ($binOut == 0); > $output += 0b1; > }elsif ($line[$x] =~ /0/) { > print "zero " if ($binOut == 0); > $output += 0b0; > } > } > print $output if ($binOut == 1); > print "\n" if ($binOut == 0); > $output = ""; > } > close $FILE; > __END__ > > A typical input is a single line of ASCII characters: "0,0,1,1,0,1,0,1," > > I expect the output to be, in binary, a single byte: 00110101 > > When I debug it with $binOut = 0 I get: zero zero one one zero one zero one > So far, so good. > > With $binOut = 1 > ./cvs2bin.pl input.csv |xxd -b > 00000000: 00110100 > > My question is, why does the ultimate "1" appear to become a zero? > Program error? > File error? > xxd error? > > Thanks, > > Eric Lucas > ___________________________________________________________________________ > Philadelphia Linux Users Group -- http://www.phillylinux.org > Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce > General Discussion -- http://lists.phillylinux.org/mailman/listinfo/plug ___________________________________________________________________________ Philadelphia Linux Users Group -- http://www.phillylinux.org Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce General Discussion -- http://lists.phillylinux.org/mailman/listinfo/plug