Solved

Formatting stings with pack and printf in perl

Posted on 2016-09-11
5
49 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thanx for explanation  

Apologies for  posting subjective question
0
 
LVL 26

Expert Comment

by:wilcoxon
Comment Utility
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Email validation in proper way is  very important validation required in any web pages. This code is self explainable except that Regular Expression which I used for pattern matching. I originally published as a thread on my website : http://www…
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…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

744 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

17 Experts available now in Live!

Get 1:1 Help Now