CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Unable to print hash value as intended

 



cf8geek
Novice

Jul 29, 2016, 2:52 PM

Post #1 of 3 (1682 views)
Unable to print hash value as intended Can't Post

I'm probably making a dumb mistake... but I have spent a couple hours troubleshooting, and can't figure it out.

I have a section of code that looks like this:


Code
print 'bridge_mainLeft_power = '; 
printStuff($bridge_mainLeft{'power'});
print ';'."\n";
print 'bridge_mainLeft_hours = ';
printStuff($bridge_mainLeft{'hours1'});
print ';'."\n";


What comes out is this:

Code
bridge_mainLeft_power = 'off'; 
';idge_mainLeft_hours = '0660
bridge_mainRight_power = 'off';

I expect that middle line to be:

Code
bridge_mainLeft_hours = '0660';

but I must be doing something wrong.

The purpose of the printStuff function is to wrap anything it gets in quotes, unless it doesn't get data, in which case it should print an error.

Code
sub printStuff { 
my $projvar = shift;
#my $projvar = $_[0];
if (defined $projvar ) { print "\'".$projvar."\'"; } else { print "\'".'GEEK_ERR'."\'"; }
}


Full files are attached, in case that helps.
Attachments: file.pl (8.27 KB)
  dumpstatus.txt (1.19 KB)


cf8geek
Novice

Jul 29, 2016, 4:24 PM

Post #2 of 3 (1679 views)
Re: [cf8geek] Unable to print hash value as intended [In reply to] Can't Post

Found it!

There must be a special character somewhere in-line; this post helped me.

Adding

Code
$value =~ s/\s+$//;

in another part of the script, has fixed the issue.


Laurent_R
Veteran / Moderator

Jul 30, 2016, 4:28 AM

Post #3 of 3 (1663 views)
Re: [cf8geek] Unable to print hash value as intended [In reply to] Can't Post

Hi,

just another possible way of coding more or less the same:


Code
print "bridge_mainLeft_power = ", defined $bridge_mainLeft{'power'} ? $bridge_mainLeft{power} : "GEEK_ERR", ";\n";


or a more concise form using the "//" operator:


Code
print "bridge_mainLeft_power = ", $bridge_mainLeft{'power'} // "GEEK_ERR", ";\n";


Or, if you think it might be easier to keep a subroutine such as printStuff, we can still simplify a bit the code:



Code
print 'bridge_mainLeft_power = ', getStuff($bridge_mainLeft{'power'}), ";\n"; 

sub getStuff {
my $projvar = shift;
return "\'".$projvar."\'"; // "\'".'GEEK_ERR'."\'";
}


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives