Stefany93 Posted November 3, 2013 Share Posted November 3, 2013 Howdy folks, After diving into Perl, I managed to write my first "program" or script rather. Basically what I wanted to do was to create an equivalent of the PHP function print_r() for displaying arrays' keys and values and thus helping for an easier debugging. Here is the script: #!/usr/bin/perl # We are telling Perl that # we shall be working in a web # browser and therefore sending # the proper HTTP headers. print "content-type: text/html \n\n"; # Perl version. use v5.16.3; # This subroutine will display # the keys and the elements # of the array # given as a subroutine parameter. sub print_r(){ # $x will iterate through the # @keys array. my $x = 0; # We collect the keys of # the given array in the # @keys array. my @keys = keys(@_); # Display 'Array' before the loop. print 'Array ( <br />'; # Iterate through the array. foreach my $value (@_){ # Print the key of the current value # using $x as an index starting at 0 # and then print the value. print ' ' . $keys[$x] . ' => ' . $value . ' <br />'; # Increment our index variable so that # the next element of the array is selected # in the next iteration. $x++; } # End of the loop. Dislaying the closing the array. print ' )'; } __END__ I have a couple of questions if you guys can help me please! 1. Shall I leave the comments as they were within the subroutine or put them above it? 2. I tried to check whether the parameter is an array with the ref() function, but the problem is that Perl subroutine parameters treats everything as an array, even empty string or a scalar variable as long as it is put as a parameter in the sub call. So I can't really think of a proper check that checks whether for example &print_r(@array) is an array. If any of you can think of tips to give me for Perl, I will be very grateful. I think Perl is an awesome language. Quote Link to comment https://forums.phpfreaks.com/topic/283568-my-first-perl-program/ Share on other sites More sharing options...
QuickOldCar Posted November 18, 2013 Share Posted November 18, 2013 wouldn't something like this work if(@array){ print "array not empty"; } else { print "array empty"; } Quote Link to comment https://forums.phpfreaks.com/topic/283568-my-first-perl-program/#findComment-1458735 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.