Fun with Perl #2 – Arrays & hard reference

Posted on Updated on

I moved to a new team this week so I haven’t had time to play around with Perl as much as I wanted .. but, I have a bit of free time to at least post something on what I thought was kinda cool but very basic.

$name = 'bill';

above is a reference to a string ‘bill’

$fooref = \$name;

is a hard reference which when run prints the following

SCALAR(0x7fa5d3006ce8)

So that was cool.. what about arrays? thats easy.

@array = ('Benji', 'Daniel', 'Ando');

and thats it. I figured to wrap everything together in 3 different subroutines/methods and run them all at the same time in some order I can see each result at the same time. So I modified my code and my result became the source below.

sub answer { 
	$name = 'bill';
	return \$name;
}

sub reference_answer { 
	$fooref = answer();
        print $fooref, "\n";
}
#! /usr/bin/perl


# サブルーチンの定義
# sub サブルーチン名 { 処理 }
# (sub + 半角スペース + サブルーチン名 + ブロック)

sub answer { 
	$name = 'bill';
	return \$name;
}

sub reference_answer { 
	$fooref = answer();
	print $fooref, "\n";
}

# &array_sub;
sub array_sub {

	# 配列を作る
	@array = ('Benji', 'Daniel', 'Ando');

	# 配列の中身を出力
	foreach $count(@array) {
		print $count, "\n";
	}	

	# 中身のハードリファレンスを出力
	foreach $count(@array) {
		print \@count, "\n";
	}
}

print "reference_answer --", reference_answer();
print "array_sub --" array_sub();

when run:

SCALAR(0x7fa5d3006ce8)
reference_answer -- 1Benji
Daniel
Ando
ARRAY(0x7fa5d300a3e0)
ARRAY(0x7fa5d300a3e0)
ARRAY(0x7fa5d300a3e0)

time to get back to work and stop playing around ..
sorry if my variable names and output results look very messy. Next time I’ll make something cool and easier to read.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s