Nano's Blog

07/20/2010

Perl trim function to strip whitespace from a string

Filed under: programming — Tags: — nano @ 09:47

Perl does not have a built-in trim function. Use the subroutine below to trim whitespace (spaces and tabs) from the beginning and end of a string in Perl. This function is directly based on the Perl FAQ entry, How do I strip blank space from the beginning/end of a string?. The ltrim and rtrim functions can trim leading or trailing whitespace.

#!/usr/bin/perl

# Declare the subroutines
sub trim($);
sub ltrim($);
sub rtrim($);

# Create a test string
my $string = "  \t  Hello world!   ";

# Here is how to output the trimmed text "Hello world!"
print trim($string)."\n";
print ltrim($string)."\n";
print rtrim($string)."\n";

# Perl trim function to remove whitespace from the start and end of the string
sub trim($)
{
	my $string = shift;
	$string =~ s/^\s+//;
	$string =~ s/\s+$//;
	return $string;
}
# Left trim function to remove leading whitespace
sub ltrim($)
{
	my $string = shift;
	$string =~ s/^\s+//;
	return $string;
}
# Right trim function to remove trailing whitespace
sub rtrim($)
{
	my $string = shift;
	$string =~ s/\s+$//;
	return $string;
}

06/29/2010

DateTime.parse Useage Sample

Filed under: programming — Tags: — nano @ 00:56

The sample code below about how to use DateTime and how to output user defined format string otherwise concatenate each character with RegEx.

stackoverflow.com

Use DateTime.TryParse or DateTime.Parse to parse the input string to a DateTime object (if you need an exact parse, there are also ParseExact and TryParseExact that take a format string).

You can then use DateTime.ToString with a custom format string that will output the exact output you want directly from DateTime objects.

DateTime.ToString(“yyyyMMddHHmmssff”);

code.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace ConAppTest
{
    class Program
    {

        static void Main(string[] args)
        {
            string s1 = ""; // date
            string s2 = ""; // time
            string s3 = "";
            string s4 = "";
            Console.WriteLine("{0}", DateTime.Now);
            s1 = DateTime.Now.ToString();
            s3 = DateTime.Parse(s1).ToString("yyyyMMddHHmmssff");
            Console.WriteLine("{0}", s3);

            Console.WriteLine("{0}", DateTime.Now.TimeOfDay);
            s2 = DateTime.Now.TimeOfDay.ToString();
            s4 = DateTime.Parse(s2).ToString("yyyyMMddHHmmssff");
            Console.WriteLine("{0}", s4);

            Regex regex1 = new Regex(@" |:|/");    //6/28/2010 2:19:21 PM
            char[] separators1 = { ' ', '/' };
            foreach (string sub1 in regex1.Split(s1))
            {
                Console.WriteLine("Word1: {0}", sub1);
            }
            // A dot (.) matches any character when used in a regular expression. You need to escape it with a backslash
            Regex regex2 = new Regex(@":|\.");  //14:19:21.8771215
            char[] separators2 = { ':', '.' };
            foreach (string sub2 in regex2.Split(s2))
            {
                Console.WriteLine("Word2: {0}", sub2);
            }
        }

    }
}

output

//6/29/2010 8:52:59 AM
//2010062908525900
//08:52:59.4604208
//2010062908525946
//Word1: 6
//Word1: 29
//Word1: 2010
//Word1: 8
//Word1: 52
//Word1: 59
//Word1: AM
//Word2: 08
//Word2: 52
//Word2: 59
//Word2: 4604208

06/17/2010

Hello World!

Filed under: programming — Tags: — nano @ 03:18

Collections:

“When was the last time you spent a pleasant evening in a comfortable chair, reading a good program.”
Jon Bentley, 1986

If you’ve been wondering about the name “C++”, now you understand. It implies “one step beyond C.”
- Thinking in C++ (2E) Bruce Eckel

06/15/2010

Generating Fibonacci Numbers Using variable-Length Arrays

Filed under: programming — Tags: — nano @ 07:28

Variable-length arrays are legal in C since C99, but if you’re using an older compiler (or compiling as C++) they won’t work.

As a workaround, you can switch to using dynamic allocation:

typedef unsigned long long uint64; // just for convenience
uint64* Fibonacci = (uint64*)malloc(sizeof(uint64)*numFibs);
// {code here}
// then at the end:
free(Fibonacci);
return 0;

Sample:

int main()
{

	int i, numFibs;

	printf("How may Fibonacci numbers do you want (between 1 to 75)? ");
	//scanf("%i", &numFibs);
        numFibs = 10;

	if ( numFibs < 1 || numFibs > 75){
	//if ( numFibs < 1 || numFibs > kMaxFibs){
		printf("Bad number, sorry!\n");
		return 1;
	}

	typedef unsigned long long uint64; // just for convenience
	uint64* Fibonacci = (uint64*)malloc(sizeof(uint64)*numFibs);

	Fibonacci[0] = 0;	// by definition
	Fibonacci[1] = 1;	// ditto

	for ( i = 2; i < numFibs; ++i)
		Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];

	for ( i = 0; i < numFibs; ++i)
		printf("%11u",Fibonacci[i]);

	printf("\n");
	free(Fibonacci);
	return 0;

}

CIS URL Links

Filed under: programming — Tags: — nano @ 01:08

Education

http://cis.stvincent.edu/html/tutorials/index.html

C

http://publications.gbdirect.co.uk/c_book/

Standard C Library

http://www.elook.org/programming/c/

06/04/2010

How to parse multi record XML file ues XML::Simple in Perl

Filed under: programming — Tags: , — nano @ 03:30

How to access multiple records

data.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
  <cd country="UK">
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <price>10.0</price>
  </cd>
  <cd country="CHN">
    <title>Greatest Hits</title>
    <artist>Dolly Parton</artist>
    <price>9.99</price>
  </cd>
  <cd country="USA">
    <title>Hello</title>
    <artist>Say Hello</artist>
    <price>0001</price>
  </cd>
</catalog>

test.pl

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

   use XML::Simple;
   use Data::Dumper;

   # create object
   my $xml = new XML::Simple;

   # read XML file
   my $data = $xml->XMLin("data.xml");

   # access XML data
   # print "$data->{name} is $data->{age} years old and works in the $data->{department} section\n";

  print $data->{cd}[0]{country}."\n";
  print $data->{cd}[0]{artist}."\n";
  print $data->{cd}[0]{price}."\n";
  print $data->{cd}[0]{title}."\n";
  print "\n\n";
  print "$data->{cd}->[0]->{country}\n";
  print "$data->{cd}->[0]->{artist}\n";
  print "$data->{cd}->[0]->{price}\n";
  print "$data->{cd}->[0]->{title}\n";

  print "\n\n";
   # print output
  print Dumper($data);

output:


D:\learning\perl>t1.pl
could not find ParserDetails.ini in C:/Perl/site/lib/XML/SAX
UK
Bonnie Tyler
10.0
Hide your heart

UK
Bonnie Tyler
10.0
Hide your heart

$VAR1 = {
          'cd' => [
                    {
                      'country' => 'UK',
                      'artist' => 'Bonnie Tyler',
                      'price' => '10.0',
                      'title' => 'Hide your heart'
                    },
                    {
                      'country' => 'CHN',
                      'artist' => 'Dolly Parton',
                      'price' => '9.99',
                      'title' => 'Greatest Hits'
                    },
                    {
                      'country' => 'USA',
                      'artist' => 'Say Hello',
                      'price' => '0001',
                      'title' => 'Hello'
                    }
                  ]
        };

D:\learning\perl>

References:

http://www.go4expert.com/forums/showthread.php?t=812

Tips:

http://www.perlmonks.org/index.pl?node_id=218480

06/03/2010

Perl Practice Scripts Collection

Filed under: programming — Tags: , — nano @ 04:57

test1.pl

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

use Data::Dumper;

my $s;

$s="status MaterializeU4";

print (($s =~ /s\s.*?((MaterializeU4)?)/) ? "Match\n" : "No Match\n");

$s="status MaterializeU4";

print (($s =~ /s\s.*?((MaterializeU4)?)/) ? "Match\n" : "No Match\n");

$s="statusaa dMaterializeU4";

print (($s =~ /s\s.*?((MaterializeU4)?)/) ? "Match\n" : "No Match\n");

$s="status < MaterializeU4>";

print (($s =~ /s\s.*?((MaterializeU4)?)/) ? "Match\n" : "No Match\n");

$s="status VIDNAME9000 = <U4 MaterializeU4()>";

print (($s =~ /s\s.*?((MaterializeU4)?)/) ? "Match\n" : "No Match\n");

# I inserted another one below
$s="status VIDNAME9000 = <U4 MaterializeU4()>";
print (($s =~ /^status .*?((MaterializeU4)?)/) ? "Match\n" : "No Match\n");

output

Match
Match
No Match
Match
Match
Match

test2.pl

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

use Data::Dumper;
my @all_lines = (
 "s 1"
,"b 1"
,""
, "status VIDNAME9000 = <U4 MaterializeU4()>"
,"b 2"
,""
, "s 3"
,"b 3"
,""

);

while (@all_lines) {
    my @block = read_block();
    print Data::Dumper->Dump([\@block]);
}
exit 0;

# Read a constant definition block from a file handle.
# void return when there is no data left in the file.
# Empty return for skippable (Materialize4U) block!!!
# Otherwise return an array ref containing lines to in the block.
sub read_block {
    my @lines = ();
    my $block_started = 0;
    my $block_ignore = 0;
    while (my $line = shift @all_lines) {
        if ($line =~ /s\s.*?((MaterializeU4)?)/){
            $block_started = 1;   # why can't execute
            $block_ignore = 1 if $1; # or is it #1?
        }
        last if $line =~ /^\s*$/ && $block_started;
        push @lines, $line unless $block_ignore;
    }
    return \@lines if @lines;
    return;
}

output

$VAR1 = [
          [
            's 1',
            'b 1'
          ]
        ];
$VAR1 = [
          [
            'status VIDNAME9000 = <U4 MaterializeU4()>',
            'b 2'
          ]
        ];
$VAR1 = [
          [
            's 3',
            'b 3'
          ]
        ];

test3.pl

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

use Data::Dumper;
my @all_lines = (
 "s 1"
,"b 1"
,""
, "status VIDNAME9000 = <U4 MaterializeU4()>"
,"b 2"
,""
, "s 3"
,"b 3"
,""

);

while (@all_lines) {
    my @block = read_block();
    print Data::Dumper->Dump([\@block]);
}
exit 0;

# Read a constant definition block from a file handle.
# void return when there is no data left in the file.
# Empty return for skippable (Materialize4U) block!!!
# Otherwise return an array ref containing lines to in the block.
sub read_block {
    my @lines = ();
    my $block_started = 0;
    my $block_ignore = 0;
    while (my $line = shift @all_lines) {
        if ($line =~ /^status .*?((MaterializeU4)?)/) {
            $block_started = 1;   # why can't execute
            $block_ignore = 1 if $1; # or is it #1?
        }
        last if $line =~ /^\s*$/ && $block_started;
        push @lines, $line unless $block_ignore;
    }
    return \@lines if @lines;
    return;
}

output

$VAR1 = [
          [
            's 1',
            'b 1'
          ]
        ];
$VAR1 = [
          [
            'status VIDNAME9000 = <U4 MaterializeU4()>',
            'b 2'
          ]
        ];
$VAR1 = [
          [
            's 3',
            'b 3'
          ]
        ];

Why test2.pl, test3.pl can’t skip the 2nd block content? thanks.

test4.pl – final

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

use Data::Dumper;
my @all_lines = (
 "s 1"
,"b 1"
,""
, "status VIDNAME9000 = <U4 MaterializeU4()>"
,"b 2"
,""
, "s 3"
,"b 3"
,""

);

while (@all_lines) {
    my @block = read_block();
    print Data::Dumper->Dump([\@block]);
}
exit 0;

# Read a constant definition block from a file handle.
# void return when there is no data left in the file.
# Empty return for skippable (Materialize4U) block!!!
# Otherwise return an array ref containing lines to in the block.
sub read_block {
    my @lines = ();
    my $block_started = 0;
    my $block_ignore = 0;
    while (my $line = shift @all_lines) {
        # original expression as below comment.
        # if ($line =~ /status\s.*?((MaterializeU4)?)/){
        if ($line =~ /^status\s.*?((MaterializeU4))/){
            $block_started = 1;   # why can't execute
            $block_ignore = 1 if $1; # or is it #1?
        }
        last if $line =~ /^\s*$/ && $block_started;
        push @lines, $line unless $block_ignore;
    }
    return \@lines if @lines;
    return;
}

output:

$VAR1 = [
          [
            's 1',
            'b 1'
          ]
        ];
$VAR1 = [];
$VAR1 = [
          [
            's 3',
            'b 3'
          ]
        ];

04/28/2010

strawberry perl

Filed under: programming — nano @ 12:28

download

http://strawberryperl.com/

pm install
open CPAN client window
input : install Encode::HanExtra (ENTER)

03/08/2010

Typeof() and GetType() in C#

Filed under: programming — Tags: — nano @ 02:05
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace testNameSpace
{

    class testClass
    {
        public static void Main()
        {
            System.Type type0 = typeof(int);
            Console.WriteLine("{0}", type0);

            int i = 0;
            System.Type type1 = i.GetType();
            Console.WriteLine("{0}", type1);

        }
    }
}

output

System.Int32
System.Int32

More:
MSDN : http://msdn.microsoft.com/en-us/library/58918ffs(VS.80).aspx

01/31/2010

pear install HTML_QuickForm

Filed under: programming — Tags: — nano @ 15:04

pear.php.net

root@mysite:~# pear install –onlyreqdeps HTML_QuickForm
PHP Warning: Module ‘imap’ already loaded in Unknown on line 0
PHP Warning: Module ‘mcrypt’ already loaded in Unknown on line 0
WARNING: “pear/HTML_QuickForm” is deprecated in favor of “pear/HTML_QuickForm2″
WARNING: “pear/HTML_Common” is deprecated in favor of “pear/HTML_Common2″
downloading HTML_QuickForm-3.2.11.tgz …
Starting to download HTML_QuickForm-3.2.11.tgz (102,201 bytes)
…………………..done: 102,201 bytes
downloading HTML_Common-1.2.5.tgz …
Starting to download HTML_Common-1.2.5.tgz (4,585 bytes)
…done: 4,585 bytes
install ok: channel://pear.php.net/HTML_Common-1.2.5
install ok: channel://pear.php.net/HTML_QuickForm-3.2.11
root@mysite:~#

Older Posts »

Powered by WordPress