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.

Nov 212010
 

Write to the middle of a file in Perl

Answer:

To write to the middle of a text file, can be easily performed by Perl.

Assume the file has 10 lines, you want to replace the 5th line:

#!/usr/bin/perl
use strict;
use Tie::File;

my $file = 'foo.txt';

tie @array, 'Tie::File', $file or die "Cannot open $file \n";

@array[4] = "Replaced!\n";

That's easy?

Nov 182010
 

Is PHP pass by reference or pass by value?

Answer:

PHP is pass by value, see the code below:

<?php

class Dog {
	
	public $name;

	public function __construct($name) {
		$this->name = $name;
	}

}

function bar($dog) {
	$dog = new Dog("bar");
	echo $dog->name;
}

$d = new Dog("foo");
echo $d->name;

bar($d);
echo $d->name;

If PHP is pass by reference, the last echo statement will print out "bar" instead of "foo", which is not true.

Nov 152010
 

What is the difference between || and or in Perl?

Answer:

In Perl, sometimes you can use both `||` and `or` to to do the same thing. But the main different is:

  • or has very low precedence, which is useful for flow control

Example:

open FILE,  $file or die("Cannot open $file");   # Work
open FILE,  $file || die("Cannot open $file");   # Does not work , because it it same as the next statement
open FILE, ($file || die("Cannot open $file"));  # Obviously not work