Reputation: 13
I am trying to convert a first decimal word of every line to binary without affecting any other words.
My code is as follows:
use strict;
use warnings;
open (tf, "dec.txt");
open (out1, " > bin.txt");
while (my $line = <tf>){
my $binary_number = sprintf("%03b", $line);
print out1 " $binary_number\n";
}
close (tf);
input file example:
3 4 5
6 7 2
1 2 3
expected output:
011 4 5
110 7 2
001 2 3
o/p from the code:
011
110
001
Is there any suggestion to achieve o/p file as per expected output? I am missing other words in the line here. those words I want to print as it is.
and also another question: is there a way to read a single column (not line)?
for example in above o/p 1st column ...
0
1
0
Upvotes: 0
Views: 129
Reputation: 198388
perl -pe 's/^(\d+)/sprintf("%03b",$1)/e' inputfile.txt
s///e
will execute the replacement as Perl code and replace the match with the result, leaving the rest unchanged.
perl -pe 's/^(\d).*/$1/' inputfile.txt
for the first character, but there are easier non-regex ways:
cut -c1 inputfile.txt
Upvotes: 2
Reputation: 29
you can split to get the first column and use sprintf to convert decimal to binary number
use lexical filehandle so that u can avoid closing the filehandle.
select is used to write the content to a new file.
#!/usr/bin/perl
use strict;
use warnings;
open my $fh, '<',"num.txt" || die "$!";
open my $wh , '>',"op.txt" || die "$!";
select ($wh);
while (my $line = <$fh>)
{
chomp($line);
my @aRR = split (/\s/,$line);
my $bin = sprintf("%03b",$aRR[0]);
print $bin," ",$aRR[1]," ", $aRR[2],"\n";
}
Upvotes: 0
Reputation: 6553
Use -a
(autosplit mode) to split on whitespace, but only modify the first column with your conversion and print the other columns unchanged:
$ perl -wane '$F[0] = sprintf("%03b", $F[0]); print "@F\n";' input.txt
Output:
011 4 5
110 7 2
001 2 3
Upvotes: 1
Reputation: 685
You can use regex anchors to achieve what you want. A regular expression like ^\d
would match a single digit at the beginning of a line.
If you need to support multi-digit numbers (like 15 or 123, for example) you can add a repetition operator: ^\d+
will match any multi-digit number at the beginning of a line.
Upvotes: -1