PHP - How to keep program still run when have error - try-catch

In the example code:
<?php
for ($i = 1; $i <=20; $i++) {
echo $i . '<br />';
if ($i == 10) {
$haha->hoho("hehe");
}
}
?>
When $i = 10 program will show this error, Call to a member function hoho() on a non-object because $haha is not a object and the program stops running. I want the program to handle this error and continue running to $i=20. How can I do it?

The Simple answer: Fix your code.
Long answer:
There is lots of ways to do that, the first thing off the top of my head is to use set_error_handler() regardless of your programming pattern.
But if you are doing it in OOP you should make use of magic methods(what?) like __call and __get -obviously the $haha needs to be the object in your example.
Hint: Using Exception in magic methods is really good idea. but
you can't handle this directly with exception because Internal PHP
functions mainly use Error reporting, only modern Object oriented
extensions use exceptions.

I would try something like:
<?php
for ($i = 1; $i <=20; $i++) {
echo $i . '<br />';
if ($i == 10) {
if ($haha) $haha->hoho("hehe");
}
}
?>
This should check if $haha exists before it tries to do $haha->hoho("hehe");

Related

Perl Program to Count Two Character Frequencies

I am trying to find two character strings in a text file and print them and their frequencies out.
#!/usr/bin/perl
#digram finder
use strict; use warnings;
#finds digrams in a file and prints them and their frequencies out
die "Must input file\n" if (#ARGV != 1);
my ($file) = #ARGV;
my %wordcount;
open (my $in, "<$file") or die "Can't open $file\n";
while (my $words = <$in>){
chomp $words;
my $length = length($words);
for (my $i = 0; $i<$length; $i++){
my $duo = substr($words, $i; 2);
if (not exists $wordcount{$duo}){
$wordcount{$duo} = 1;
}
else {
$wordcount{$duo}++;
}
}
}
foreach my $word (sort {$wordcount{$b} cmp $wordcount{$a}} keys %wordcount){
print "$word\t$wordcount{$duo}\n";
}
close($in);
First I set the text file to a string $words.
Then, I run a for loop and create a substring $duo at each position along $words
If $duo doesn't exist within the hash %wordcount, then the program creates the key $duo
If $duo does exist, then the count for that key goes up by 1
Then the program prints out the digrams and their frequencies, in order of decreasing frequency
When I try to run the code, I get the error message that I forgot to declare $word on line 17 but I do not even have the string $word. I am not sure where this error message is coming from. Can someone help me find where the error is coming from?
Thank you
My best guess is that you actually have $word instead of $words; a typo. If the compilation found the symbol $word in the text then it's probably there.
However, I'd also like to comment on the code. A cleaned up version
while (my $words = <$in>) {
chomp $words;
my $last_duo_idx = length($words) - 2;
for my $i (0 .. $last_duo_idx) {
my $duo = substr($words, $i, 2);
++$wordcount{$duo};
}
}
my #skeys = sort { $wordcount{$b} <=> $wordcount{$a} } keys %wordcount;
foreach my $word (#skeys) {
print "$word\t$wordcount{$word}\n";
}
This runs correctly on a made-up file. (I sort separately only so to not run off of the page.)
Comments
Need to stop one before last in the line, and substr starts from 0; thus -2
One almost never needs a C-style loop
There is no need here to test for existence of a key. If it doesn't exist it is autovivified (created), then incremented to 1 with ++; otherwise the count is incremented.
To sort numerically use <=>, not cmp
Typos:
substr($words, $i; 2) needs a , not ;, so substr($words, $i, 2)
$wordcount{$duo} in print should be $wordcount{$word}.
I am not sure about naming: why is a line of text called $words?

Showing nested for loops in a flowchart

How could I show a nested loop in a flowchart?
I want to show a nested foreach loop in a flowchart that shows something like this
foreach($array as $item) {
foreach($SecondArray as $key=>$value) {
// Do stuff...
}
}
Now correct me if I'm wrong, but there is no way to show a foreach loop in a flowchart, so I'd need to show a for loop in the diagram(?) So the algorithm should be shown as something more like:
for ($i = 0; $i < count($array); i++) {
for ($j = 0; $j < count($arrayTwo); $j++) {
// Do stuff...
}
}
Now looking at the answers to this question (How to picture “for” loop in block representation of algorithm), a single for loop could be shown like this:
But I cannot think of any way in which I could show a nested loop (to show the code I wrote above).
Any suggestions?
This is what you are looking for.
You can see other interesting flowchart for nested loops here.

Counting how many numbers greater than 5 in a given array

I am having an error saying that prototype not terminated at filename.txt line number 113 where as line number 113 belongs to a different program which is running successfully.
sub howmany(
my #H = #_;
my $m = 0;
foreach $x (#H) {
if ( $x > 5 ) {
$m +=1;
}
else {
$m +=0;
}
}
print "Number of elements greater than 5 is equal to: $m \n";
}
howmany(1,6,9);
The sub keyword should be followed by { } not ( ) (if you define a simple function), that's why the error
prototype not terminated
After this, always start with : use strict; use warnings;
Put this and debug your script, there's more errors.
Last but not least, indent your code properly, using an editor with syntax highlighting, you will save many time debugging
The error is due to parenthesis.
Never do $m += 0; As you actually load processor for nothing. Of course it's not gonna be visible on such a small function, but...
sub howmany {
my $m = 0;
foreach (#_) {
$m++ if ($_ > 5);
}
print "Number of elements greater than 5 is equal to: $m \n";
}
howmany(1,6,9);

inserting numeric results of a function into perl array using a for loop

i am new to perl and i want to do something similar to what i do in C.
for(i=0;i<32;i++)
{
array[i]= some_function_result();
}
and then print the array
and for doing this, what i am trying to do in perl is
#data=();
for($i=0;$i<32;$i++){
$hexval = unpack('H2',substr($payload,$i,1));
#data[$i]=$hexval;
}
print #data;
is this correct?
i tried to use the functions like push(#data,$hexval) but that resulted in
32
64
96...
i know this is naive..but can someone help me out with this please..
int i;
for (i=0; i<32; i++) {
array[i]= some_function_result();
}
is
for (my $i=0; $i<32; $i++) {
$array[$i] = some_function_result();
}
or better yet
for my $i (0..31) {
$array[$i] = some_function_result();
}
Flow control statements are documented in perlsyn.
Variable types are documented in perldata.
(Accessible using perldoc perlsyn or even man perlsyn.)
You should indeed always use use strict; use warnings;.

How to Create interruptible loop in mel

Is there a way to make a loop which can be interrupted or cancelled in MEL (Maya Embedded Language)?
You should use a progress bar. Example straight from the manual:
{
global string $gMainProgressBar; // This is defined on maya startup
progressBar -edit
-beginProgress
-isInterruptable true
-status "Example Calculation ..."
-maxValue 5000
$gMainProgressBar;
int $i;
for($i=0; $i < 5000; $i++) {
if(`progressBar -query -isCancelled $gMainProgressBar`)
break;
progressBar -edit
-step 1 $gMainProgressBar;
}
progressBar -edit
-endProgress
$gMainProgressBar;
}
Maya now shows progress and allows you to use esc to interrupt.
You can use break instruction. For example:
string $joints[] = {"joint1","joint2","joint3","joint4","joint5","joint6"};
for ($i = 0; $i < size($joints); $i++) {
if ($i > 3){
break;
}
print $joints[$i];
}
will print only first 4 elements: joint1 joint2 joint3 joint4

Resources