I'm using the printf function to display some textual information. It is possible that the string may contain different symbols such as $#%^&* somewhere within the text.

I know that to handle the % that I need to use a %% to make the string evaluate correctly.
for example:

printf "strin%%g";

will display as strin%g <-- what I want

My question is are there any other symbols that will give me issue using printf like % does? and if so, how do I handle them?


Thanks so much!

It's very similar to C's printf(). In perl, the following are equivalent:

print "strin%g";
printf("strin%%g");
printf "strin%%g";
printf("%s","strin%g");
printf "%s","strin%g";

For printf, the first string is the format string. Google "perl printf format"; the third result (for me) was http://www.tutorialspoint.com/perl/perl_printf.htm.

#!/usr/bin/perl;
use strict; 
use warnings; 

printf("Dollar %s\nPound %s\nPercent %s\nCarot %s\nAmpersand %s",
       ('$', '#', '%', '^', '&', '*'));

#Outputs
#Dollar $
#Pound #
#Percent %
#Carot ^
#Ampersand &

I'm not sure I understand the question. You ask about symbols occurring within the text but your example shows a percent sign occurring within the printf format argument. I think the answer is 'No, other symbols will not cause a problem for printf.'

However, keep in mind that anything between double quotes will interpolate, so use single quotes for your text argument so perl won't attempt to interpolate strings including $, @, %, \, etc.

Thanks that's what I was looking for... The thing is that I will be interpolating in my printf statement. However, the script is setup to where the file name that is also being printed in the statement may have a % sign in it once it gets to me. So when this case happens I am getting errors thrown back.
Unfortunately, this is how it has to be with the data I am working with as I cannot change the file name before it gets to me. I can however, add an extra percent sign in order to stop the error.

Sorry for not wording it more clearly. My main concern was if for some reason the percent sign happens to be a dollar sign or an ampersand this go around, am I going to throw errors. I appreciate your help.. I am very new to perl still, though I have been programming for a while, and just started a project where I have to use it.

This article has been dead for over six months. Start a new discussion instead.