Solved

Formatting stings with pack and printf in perl

Posted on 2016-09-11
5
67 Views
Last Modified: 2016-09-12
Hi

I need to format a string with a fixed width so I've been playing with pack and sprintf to ad leading and trailing white space

my $string = "Hello";
print " short string $string;\n";

my $len;
($string,$len) = packString($string);

print "\nafter pack [$string] $len\n";
($string,$len) = sprintfString($string);
print "\nafter sprintf [$string] $len\n";

my $LongString ="Lorem ipsum dolor sit amet consectetuer auctor Curabitur.";

($LongString,$len)= packString($LongString);

print "\nLorem after pack [$LongString]  $len\n";
($LongString,$len)= sprintfString($LongString);

print "\nLorem after sprintf [$LongString]  $len\n";

print "\n6[";	
printf("%6s", 'foo'); 
print "] space B4 foo\n["; 
printf("%-6s", 'foo');
print "]space after foo\n[";	


printf("%-6s", "%10s", 'foo');
print "]space B4 & after  foo\n";


sub packString{
    my $string = shift;
    $string = pack("A20", $string);
    my $len = length($string);
    return ($string,$len);
    }
    
sub sprintfString{
    my $string = shift;
    $string = sprintf("%20s", $string, "%20s" );
    my $len = length($string);
    return ($string,$len);
    }
    

Open in new window


## output  from above
 short string Hello;

after pack [Hello               ] 20

after sprintf [Hello               ] 20

Lorem after pack [Lorem ipsum dolor si]  20

Lorem after sprintf [Lorem ipsum dolor si]  20

6[   foo] space B4 foo
[foo   ]space after foo
[%10s  ]space B4 & after  foo

Open in new window


1st  Which is the better option
2nd how do I add white space before and after foo on one line?
0
Comment
Question by:trevor1940
  • 2
  • 2
5 Comments
 
LVL 28

Expert Comment

by:FishMonger
ID: 41793667
I'm not sure I understand why you want/need to use pack and  it's unclear what output you expect.

Please supply a more realistic sample of your input data, about 10 lines, and what you expect as output.
0
 
LVL 1

Author Comment

by:trevor1940
ID: 41793826
Erm?

I need to output I string at a fixed length of 20 characters if necessary adding extra spaces  to the end or cutting the end off so i'm wondering what is the best way of doing it

pack

    $string = pack("A20", $string);
    print "pack [$string]\n";

Open in new window


or sprintf
    $string = sprintf("%20s", $string );
    print "sprintf [$string]\n";

Open in new window


Output for both

pack [Hello               ] 

sprintf [Hello               ]

pack [Lorem ipsum dolor si]

sprintf [Lorem ipsum dolor si]

Open in new window


Which is the better option?

Taking it one step further If I need to add spaces at both begging and end how might I do this

 my $foo = 'foo';
printf("%-6s", "%10s", $foo';
output 6 spaces before & 10 after

[       foo          ]  ## brackets for show only

Open in new window

0
 
LVL 28

Accepted Solution

by:
FishMonger earned 500 total points
ID: 41794486
Restating the same question without providing more info doesn't help much.

If the string is greater than 20 characters and you only want to output 20 of those characters, then the most obvious method would be to use the substr() function, next would be a regex and the 3rd would be the pack() function.  My choice would be the substr() function because it's the most self documenting of the three.

If the string is less than 20 characters and you want it left or right justified, then sprintf() would be the most obvious choice.  If it's going to be left justified, then the pack() function is also an option, but not if you need/want it right justified.

If it's under 20 chars and you want it space padded on both sides to a total length of 20, you need to determine how many spaces will be required and how much of that you want on each side.  Once that determination is made my choice would be to use sprintf() to output it.

So far I have not stated which is "best" because that is subjective.  "Best" in what way?  Readability, maintainability, performance, etc?  IMO, readability and maintainability should be the first consideration.  I look at performance issues after the script is written and profiled.  Premature optimizations are almost always a waste of effort.

If you are concerned with the performance, then write a short Benchmark test script comparing the difference between those methods and see which one is the fastest and by how much.
0
 
LVL 1

Author Closing Comment

by:trevor1940
ID: 41794602
Thanx for explanation  

Apologies for  posting subjective question
0
 
LVL 26

Expert Comment

by:wilcoxon
ID: 41795101
As usual, FishMonger gave you a full explanation of options and I agree with what he said.

The way I'd do what you want would be:
$output = sprintf '%20s', substr($input, 0, 20);
# if you want left-justified, make it %-20s
# if you want center-justified, it gets more complicated

Open in new window

1

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Perl strange behaviour 5 67
Search in text file in column and compare 4 46
.properties file to call function/method 9 59
PERL - Find newest folder 12 113
I have been pestered over the years to produce and distribute regular data extracts, and often the request have explicitly requested the data be emailed as an Excel attachement; specifically Excel, as it appears: CSV files confuse (no Red or Green h…
There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now