Tuesday, June 19, 2012

Extracting alternate items from an array in Perl

Hmm.. I forgot which web page I referred to, but this is a 2-liner code to extract the odd-th numbered items, or even-th numbered items in an array. :)




use Data::Dumper;$Data::Dumper::Indent = 3;


@array = ( 1, 2, 3, 4, 5, 6, 7 );


$flag = 0;
@oddth = grep {$flag ^= 1} @array;


print Dumper(\@oddth);
print "\n";


$flag = 1;
@eventh = grep {$flag ^= 1} @array;


print Dumper(\@eventh);
print "\n";



output :



Rails - to create a blog site Part 3 [basic validation]

By default, there is no validation on the input on the form that we have created. The validation code shall be put in the model file.

Oh, I just realize that I did not mention about MVC. MVC stand for Model-View-Controller. It is a kind of software pattern that separate the application into 3 components. The model is the application object, the controller defines the application interface, while the view defines the presentation. For more information, can go wiki to check it out. :)

The model file resides in <root directory>/app/models. For my example, the file is blog/app/models/test_j.rb.



The TestJ class is a sub class of ActiveRecord::Base. The attr_accessible is to specify what are the attributes can be updated.

I tried to remove the tag from the attr_accessible and try to create a new record, this is the error observed.



This is only experimental testing. I am not sure how this is to be done to have the error message displayed nicely instead of giving internal error. The best way I can figure out is, remove the input from create new page directly. :)

Back to the topic that I want to discuss here. Normally, in a form, we'll have required field. To validate the required field(s) has been filled, add the lines to validate the presence of the input. The length attribute controls the required length of the input of the field.



For length, you can specified :in, :is, :minimum or :maximum.

The application will have the default error message printed on the form if the validation failed.




More information about the validation, please visit http://guides.rubyonrails.org/active_record_validations_callbacks.html