--- name: bless signatures: - 'bless REF, CLASSNAME' - 'bless REF' since: 5.0 status: documented categories: ["Classes and OO"] --- ```{index} single: bless; Perl built-in ``` *[Classes and OO](../perlfunc-by-category)* # bless Mark the thing a reference points at as an object in a package. `bless` associates the referent of `REF` with the package named by `CLASSNAME`, so that method calls through `REF` dispatch against that package's subroutines (and its [`@ISA`](../perlvar) ancestors). The reference itself does not change; what changes is the referent's class tag. `bless` returns `REF`, which is why it is almost always the last statement in a constructor. ## Synopsis ```perl bless REF, CLASSNAME bless REF ``` ## What you get back The same reference that was passed in as the first argument, now carrying the class tag of `CLASSNAME`. Returning the reference lets you tail-call `bless` from a constructor: ```perl sub new { my ($class, %args) = @_; return bless { %args }, $class; } ``` From that point on, [`ref`](ref) on the returned reference yields the class name rather than the raw reference type (`HASH`, `ARRAY`, `CODE`, ...). ## Forms Two calling forms, one strongly preferred: - **Two-argument — always use this.** ```perl bless $ref, $class; ``` The referent becomes an object in the package named by `$class`. Using the first argument of the constructor (`$_[0]`, conventionally `$class`) keeps the constructor inheritable: a subclass calling `Parent::new('Child', ...)` gets back an object blessed into `Child`, not into `Parent`. - **Two-argument with empty string — bless into `main`.** ```perl bless $ref, ""; ``` An empty `CLASSNAME` is treated as the `main` package. Rarely useful outside of deliberate tricks. - **One-argument — discouraged.** ```perl bless $ref; ``` The referent is blessed into the *current* package (the package the `bless` call is compiled in). This breaks inheritance: a subclass that inherits a one-argument `bless` constructor still ends up with objects in the parent's package, not the caller's. Use the two-argument form unless you have a concrete reason not to, and document the reason. ## Examples A minimal hash-based class: ```perl package Point; sub new { my ($class, $x, $y) = @_; return bless { x => $x, y => $y }, $class; } sub x { $_[0]->{x} } sub y { $_[0]->{y} } package main; my $p = Point->new(3, 4); print ref $p, "\n"; # Point print $p->x, ",", $p->y; # 3,4 ``` Inheritable constructor — the same `new` works for a subclass without modification: ```perl package Shape; sub new { my ($class, %args) = @_; return bless { %args }, $class; } package Circle; our @ISA = ('Shape'); sub area { my $self = shift; return 3.14159 * $self->{radius} ** 2; } package main; my $c = Circle->new(radius => 5); print ref $c, "\n"; # Circle print $c->area, "\n"; # 78.53975 ``` Array-based objects work the same way — any reference type can be blessed: ```perl package Pair; sub new { my ($class, $a, $b) = @_; return bless [$a, $b], $class; } sub first { $_[0]->[0] } sub second { $_[0]->[1] } my $p = Pair->new("left", "right"); print $p->first, "/", $p->second; # left/right ``` Re-blessing an existing object changes its class tag in place: ```perl my $obj = bless {}, 'OldClass'; bless $obj, 'NewClass'; print ref $obj; # NewClass ``` `bless` returns the reference, which is why chaining into method calls on the same line works: ```perl Logger->new(file => $path)->info("started"); # ^ called on the blessed ref ``` ## Edge cases - **The reference is what gets tagged, not the variable.** Copies of the reference share the class tag because they all point to the same referent: ```perl my $a = bless {}, 'Foo'; my $b = $a; print ref $b; # Foo ``` - **Re-blessing is permitted and immediate.** A reference can be blessed as many times as you like; each call overwrites the previous class tag. There is no "unbless" built-in — rebless into a neutral package if you need to strip objecthood from a referent you still hold references to. - **`CLASSNAME` of `""` means `main`.** Explicit and rarely wanted; usually a sign that a computed class name came out empty by accident. - **Avoid `bless $ref, "0"`.** The class name `"0"` is a false value, so code that checks `if (ref $obj) { ... }` will misread the object as "not a reference". Pick any non-false class name. - **Class-name casing convention.** Use mixed-case (`My::Package`). ALL-CAPS names are reserved for Perl built-in types (`SCALAR`, `ARRAY`, `HASH`, `CODE`, ...) and all-lowercase names are reserved for pragmas (`strict`, `warnings`, `utf8`). Blessing into either namespace invites confusion with language-level machinery. - **Non-reference first argument is a fatal error.** `bless 42, 'Foo'` dies with `Can't bless non-reference value`. The first argument must be a reference. - **One-argument `bless` picks the compile-time package.** It uses the package the `bless` call is *lexically* inside — not the caller's package, not the package of `$class`. That is exactly why it breaks inheritance and why the two-argument form exists. - **Weak references and blessing interact as expected.** `Scalar::Util::weaken` on a blessed reference does not unbless it; the weakened slot still sees the class tag, and [`ref`](ref) works until the referent is destroyed. - **`DESTROY` fires on the blessed referent.** When the last reference to a blessed referent goes away, Perl calls `DESTROY` in the reference's class (following [`@ISA`](../perlvar)). Changing the class with a late `bless` changes which `DESTROY` runs. ## Differences from upstream Fully compatible with upstream Perl 5.42. ## See also - [`ref`](ref) — read the class tag back off a blessed reference, or the reference type (`HASH`, `ARRAY`, ...) for an unblessed one - [`package`](package) — declare the package a `bless` call or a subroutine definition compiles into; the target of one-argument `bless` - [`class`](class) — the experimental class-syntax built-in that replaces the hand-rolled `package` + `bless` constructor pattern with declarative syntax - [`tie`](tie) — a different form of per-variable magic; unrelated to `bless` despite the superficial "attach behaviour to a value" framing - [`@ISA`](../perlvar) — the inheritance chain consulted when dispatching a method call on a blessed reference - `DESTROY` — the destructor method Perl calls on the blessed referent when its last reference goes away; declared as a subroutine inside the class's package