Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Sep 102010
 

Generate new list using map in Perl

Answer:

The Perl's map function is superb cool for generating new list based on an existing list.

1. Generate new array based on an existing array

my @new = map {$_ * 2} (1, 2, 3);

# @new contains 2, 4, 6

2. Generate new hash based on an existing array

my %new = map {$_ => 1} (1,2,3);

# %new contains a hash...
#      {
#           '1' => 1,
#           '3' => 1,
#           '2' => 1
#       };


Sep 082010
 

Generate UUID in PHP

Answer:

To generate UUID in PHP, you can try the script below:

<?php

function uuid($prefix = '') {
    $chars = md5(uniqid(mt_rand(), true));
    $uuid  = substr($chars,0,8) . '-';
    $uuid .= substr($chars,8,4) . '-';
    $uuid .= substr($chars,12,4) . '-';
    $uuid .= substr($chars,16,4) . '-';
    $uuid .= substr($chars,20,12);
    return $prefix . $uuid;
}

echo uuid();

It shows something like the following when executed:

c664b9b4-6c44-c8d9-acf9-93ef0e11e435

Sep 062010
 

Clone an object in PHP

Answer:

It is easy to clone an object in PHP, using the following method.

<?php

    $obj = new stdClass(); 
    $obj->foo = "foo";
    $obj->bar = "bar";

    $new_obj = clone $obj;
    var_dump ( new_obj );

It will print out...

object(stdClass)#2 (2) {
  ["foo"]=>
  string(3) "foo"
  ["bar"]=>
  string(3) "bar"
}