CINXE.COM
perlclass - Perl class syntax reference - Perldoc Browser
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>perlclass - Perl class syntax reference - Perldoc Browser</title> <link rel="search" href="/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser"> <link rel="canonical" href="https://perldoc.perl.org/perlclass"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" /> <style> body { background: #f4f4f5; color: #020202; } .navbar-dark { background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%); background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%); background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0); background-repeat: repeat-x; } .navbar-dark .navbar-nav .nav-link, .navbar-dark .navbar-nav .nav-link:focus { color: #fff } .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 } #wrapperlicious { margin: 0 auto; font: 0.9em 'Helvetica Neue', Helvetica, sans-serif; font-weight: normal; line-height: 1.5em; margin: 0; padding: 0; } #wrapperlicious h1 { font-size: 1.5em } #wrapperlicious h2 { font-size: 1.3em } #wrapperlicious h3 { font-size: 1.1em } #wrapperlicious h4 { font-size: 0.9em } #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3, #wrapperlicious h4, #wrapperlicious dt { color: #020202; margin-top: 1em; margin-bottom: 1em; position: relative; font-weight: bold; } #wrapperlicious a { color: inherit; text-decoration: underline } #wrapperlicious #toc { text-decoration: none } #wrapperlicious a:hover { color: #2a2a2a } #wrapperlicious a img { border: 0 } #wrapperlicious :not(pre) > code { color: inherit; background-color: rgba(0, 0, 0, 0.04); border-radius: 3px; font: 0.9em Consolas, Menlo, Monaco, monospace; padding: 0.3em; } #wrapperlicious dd { margin: 0; margin-left: 2em; } #wrapperlicious dt { color: #2a2a2a; font-weight: bold; margin-left: 0.9em; } #wrapperlicious p { margin-bottom: 1em; margin-top: 1em; } #wrapperlicious li > p { margin-bottom: 0; margin-top: 0; } #wrapperlicious pre { border: 1px solid #c1c1c1; border-radius: 3px; font: 100% Consolas, Menlo, Monaco, monospace; margin-bottom: 1em; margin-top: 1em; } #wrapperlicious pre > code { display: block; background-color: #f6f6f6; font: 0.9em Consolas, Menlo, Monaco, monospace; line-height: 1.5em; text-align: left; white-space: pre; padding: 1em; } #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul { margin-bottom: 1em; margin-top: 1em; } #wrapperlicious ul { list-style-type: square; } #wrapperlicious ul ul { margin-bottom: 0px; margin-top: 0px; } #footer { font-size: 0.8em; padding-top: 0.5em; text-align: center; } #more { display: inline; font-size: 0.8em; } #perldocdiv { background-color: #fff; border: 1px solid #c1c1c1; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; margin-left: auto; margin-right: auto; padding: 3em; padding-top: 1em; max-width: 960px; } #moduleversion { float: right } #wrapperlicious .leading-notice { font-style: italic; padding-left: 1em; margin-top: 1em; margin-bottom: 1em; } #wrapperlicious .permalink { display: none; left: -0.75em; position: absolute; padding-right: 0.25em; text-decoration: none; } #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink, #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink, #wrapperlicious dt:hover .permalink { display: block; } </style> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-KVNWBNT5FB'); gtag('config', 'UA-50555-3'); </script> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="/"><img src="/images/perl_camel_30.png" width="30" height="30" class="d-inline-block align-top" alt="Perl Camel Logo"> Perldoc Browser</a> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav mr-auto"> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">blead</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-stable"> <a class="dropdown-item" href="/perlclass">Latest</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.40.1/perlclass">5.40.1</a> <a class="dropdown-item" href="/5.40.0/perlclass">5.40.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.38.3/perlclass">5.38.3</a> <a class="dropdown-item" href="/5.38.2/perlclass">5.38.2</a> <a class="dropdown-item" href="/5.38.1/perlclass">5.38.1</a> <a class="dropdown-item" href="/5.38.0/perlclass">5.38.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.36.3/perlclass">5.36.3</a> <a class="dropdown-item" href="/5.36.2/perlclass">5.36.2</a> <a class="dropdown-item" href="/5.36.1/perlclass">5.36.1</a> <a class="dropdown-item" href="/5.36.0/perlclass">5.36.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.34.3/perlclass">5.34.3</a> <a class="dropdown-item" href="/5.34.2/perlclass">5.34.2</a> <a class="dropdown-item" href="/5.34.1/perlclass">5.34.1</a> <a class="dropdown-item" href="/5.34.0/perlclass">5.34.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.32.1/perlclass">5.32.1</a> <a class="dropdown-item" href="/5.32.0/perlclass">5.32.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.30.3/perlclass">5.30.3</a> <a class="dropdown-item" href="/5.30.2/perlclass">5.30.2</a> <a class="dropdown-item" href="/5.30.1/perlclass">5.30.1</a> <a class="dropdown-item" href="/5.30.0/perlclass">5.30.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.28.3/perlclass">5.28.3</a> <a class="dropdown-item" href="/5.28.2/perlclass">5.28.2</a> <a class="dropdown-item" href="/5.28.1/perlclass">5.28.1</a> <a class="dropdown-item" href="/5.28.0/perlclass">5.28.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.26.3/perlclass">5.26.3</a> <a class="dropdown-item" href="/5.26.2/perlclass">5.26.2</a> <a class="dropdown-item" href="/5.26.1/perlclass">5.26.1</a> <a class="dropdown-item" href="/5.26.0/perlclass">5.26.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.24.4/perlclass">5.24.4</a> <a class="dropdown-item" href="/5.24.3/perlclass">5.24.3</a> <a class="dropdown-item" href="/5.24.2/perlclass">5.24.2</a> <a class="dropdown-item" href="/5.24.1/perlclass">5.24.1</a> <a class="dropdown-item" href="/5.24.0/perlclass">5.24.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.22.4/perlclass">5.22.4</a> <a class="dropdown-item" href="/5.22.3/perlclass">5.22.3</a> <a class="dropdown-item" href="/5.22.2/perlclass">5.22.2</a> <a class="dropdown-item" href="/5.22.1/perlclass">5.22.1</a> <a class="dropdown-item" href="/5.22.0/perlclass">5.22.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.20.3/perlclass">5.20.3</a> <a class="dropdown-item" href="/5.20.2/perlclass">5.20.2</a> <a class="dropdown-item" href="/5.20.1/perlclass">5.20.1</a> <a class="dropdown-item" href="/5.20.0/perlclass">5.20.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.18.4/perlclass">5.18.4</a> <a class="dropdown-item" href="/5.18.3/perlclass">5.18.3</a> <a class="dropdown-item" href="/5.18.2/perlclass">5.18.2</a> <a class="dropdown-item" href="/5.18.1/perlclass">5.18.1</a> <a class="dropdown-item" href="/5.18.0/perlclass">5.18.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.16.3/perlclass">5.16.3</a> <a class="dropdown-item" href="/5.16.2/perlclass">5.16.2</a> <a class="dropdown-item" href="/5.16.1/perlclass">5.16.1</a> <a class="dropdown-item" href="/5.16.0/perlclass">5.16.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.14.4/perlclass">5.14.4</a> <a class="dropdown-item" href="/5.14.3/perlclass">5.14.3</a> <a class="dropdown-item" href="/5.14.2/perlclass">5.14.2</a> <a class="dropdown-item" href="/5.14.1/perlclass">5.14.1</a> <a class="dropdown-item" href="/5.14.0/perlclass">5.14.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.12.5/perlclass">5.12.5</a> <a class="dropdown-item" href="/5.12.4/perlclass">5.12.4</a> <a class="dropdown-item" href="/5.12.3/perlclass">5.12.3</a> <a class="dropdown-item" href="/5.12.2/perlclass">5.12.2</a> <a class="dropdown-item" href="/5.12.1/perlclass">5.12.1</a> <a class="dropdown-item" href="/5.12.0/perlclass">5.12.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.10.1/perlclass">5.10.1</a> <a class="dropdown-item" href="/5.10.0/perlclass">5.10.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.8.9/perlclass">5.8.9</a> <a class="dropdown-item" href="/5.8.8/perlclass">5.8.8</a> <a class="dropdown-item" href="/5.8.7/perlclass">5.8.7</a> <a class="dropdown-item" href="/5.8.6/perlclass">5.8.6</a> <a class="dropdown-item" href="/5.8.5/perlclass">5.8.5</a> <a class="dropdown-item" href="/5.8.4/perlclass">5.8.4</a> <a class="dropdown-item" href="/5.8.3/perlclass">5.8.3</a> <a class="dropdown-item" href="/5.8.2/perlclass">5.8.2</a> <a class="dropdown-item" href="/5.8.1/perlclass">5.8.1</a> <a class="dropdown-item" href="/5.8.0/perlclass">5.8.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.6.2/perlclass">5.6.2</a> <a class="dropdown-item" href="/5.6.1/perlclass">5.6.1</a> <a class="dropdown-item" href="/5.6.0/perlclass">5.6.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.005_04/perlclass">5.005_04</a> <a class="dropdown-item" href="/5.005_03/perlclass">5.005_03</a> <a class="dropdown-item" href="/5.005_02/perlclass">5.005_02</a> <a class="dropdown-item" href="/5.005_01/perlclass">5.005_01</a> <a class="dropdown-item" href="/5.005/perlclass">5.005</a> </div> </li> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-dev"> <a class="dropdown-item active" href="/blead/perlclass">blead</a> <a class="dropdown-item" href="/5.41.10/perlclass">5.41.10</a> <a class="dropdown-item" href="/5.41.9/perlclass">5.41.9</a> <a class="dropdown-item" href="/5.41.8/perlclass">5.41.8</a> <a class="dropdown-item" href="/5.41.7/perlclass">5.41.7</a> <a class="dropdown-item" href="/5.41.6/perlclass">5.41.6</a> <a class="dropdown-item" href="/5.41.5/perlclass">5.41.5</a> <a class="dropdown-item" href="/5.41.4/perlclass">5.41.4</a> <a class="dropdown-item" href="/5.41.3/perlclass">5.41.3</a> <a class="dropdown-item" href="/5.41.2/perlclass">5.41.2</a> <a class="dropdown-item" href="/5.41.1/perlclass">5.41.1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.40.1-RC1/perlclass">5.40.1-RC1</a> <a class="dropdown-item" href="/5.40.0-RC2/perlclass">5.40.0-RC2</a> <a class="dropdown-item" href="/5.40.0-RC1/perlclass">5.40.0-RC1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.39.10/perlclass">5.39.10</a> <a class="dropdown-item" href="/5.39.9/perlclass">5.39.9</a> <a class="dropdown-item" href="/5.39.8/perlclass">5.39.8</a> <a class="dropdown-item" href="/5.39.7/perlclass">5.39.7</a> <a class="dropdown-item" href="/5.39.6/perlclass">5.39.6</a> <a class="dropdown-item" href="/5.39.5/perlclass">5.39.5</a> <a class="dropdown-item" href="/5.39.4/perlclass">5.39.4</a> <a class="dropdown-item" href="/5.39.3/perlclass">5.39.3</a> <a class="dropdown-item" href="/5.39.2/perlclass">5.39.2</a> <a class="dropdown-item" href="/5.39.1/perlclass">5.39.1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.38.3-RC1/perlclass">5.38.3-RC1</a> </div> </li> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-nav"> <a class="dropdown-item" href="/blead/perl">Perl</a> <a class="dropdown-item" href="/blead/perlintro">Intro</a> <a class="dropdown-item" href="/blead/perl#Tutorials">Tutorials</a> <a class="dropdown-item" href="/blead/perlfaq">FAQs</a> <a class="dropdown-item" href="/blead/perl#Reference-Manual">Reference</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/blead/perlop">Operators</a> <a class="dropdown-item" href="/blead/functions">Functions</a> <a class="dropdown-item" href="/blead/variables">Variables</a> <a class="dropdown-item" href="/blead/modules">Modules</a> <a class="dropdown-item" href="/blead/perlutil">Utilities</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/blead/perldelta">Release Notes</a> <a class="dropdown-item" href="/blead/perlcommunity">Community</a> <a class="dropdown-item" href="/blead/perlhist">History</a> </div> </li> </ul> <ul class="navbar-nav"> <script> function set_expand (expand) { var perldocdiv = document.getElementById('perldocdiv'); var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width'); var expanded = (width == '' || width == 'none') ? true : false; if (expand === null) { expand = !expanded; } if ((expand && !expanded) || (!expand && expanded)) { perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px'); var button_classlist = document.getElementById('content-expand-button').classList; if (expand) { button_classlist.add('btn-light'); button_classlist.remove('btn-outline-light'); } else { button_classlist.add('btn-outline-light'); button_classlist.remove('btn-light'); } } return expand; } function toggle_expand () { var expand = set_expand(null); document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC'; } function read_expand () { return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 }); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { if (read_expand()) { set_expand(true); } }); } else if (read_expand()) { set_expand(true); } </script> <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-4" onclick="toggle_expand()">Expand</button> </ul> <form class="form-inline" method="get" action="/blead/search"> <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search" value=""> </form> </div> </nav> <div id="wrapperlicious" class="container-fluid"> <div id="perldocdiv"> <div id="links"> <a href="/blead/perlclass">perlclass</a> <div id="more"> (<a href="/blead/perlclass.txt">source</a>, <a href="https://metacpan.org/pod/perlclass">CPAN</a>) </div> </div> <div class="leading-notice"> You are viewing the version of this documentation from Perl blead. This is a development version of Perl. </div> <h1><a id="toc">CONTENTS</a></h1> <ul> <li> <a class="text-decoration-none" href="#NAME">NAME</a> </li> <li> <a class="text-decoration-none" href="#SYNOPSIS">SYNOPSIS</a> </li> <li> <a class="text-decoration-none" href="#DESCRIPTION">DESCRIPTION</a> <ul> <li> <a class="text-decoration-none" href="#History">History</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#KEYWORDS">KEYWORDS</a> <ul> <li> <a class="text-decoration-none" href="#class">class</a> </li> <li> <a class="text-decoration-none" href="#field">field</a> </li> <li> <a class="text-decoration-none" href="#method">method</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#ATTRIBUTES">ATTRIBUTES</a> <ul> <li> <a class="text-decoration-none" href="#Class-attributes">Class attributes</a> <ul> <li> <a class="text-decoration-none" href="#:isa">:isa</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#Field-attributes">Field attributes</a> <ul> <li> <a class="text-decoration-none" href="#:param">:param</a> </li> <li> <a class="text-decoration-none" href="#:reader">:reader</a> </li> <li> <a class="text-decoration-none" href="#:writer">:writer</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#Method-attributes">Method attributes</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#OBJECT-LIFECYCLE">OBJECT LIFECYCLE</a> <ul> <li> <a class="text-decoration-none" href="#Construction">Construction</a> </li> <li> <a class="text-decoration-none" href="#Adjustment">Adjustment</a> </li> <li> <a class="text-decoration-none" href="#Lifetime">Lifetime</a> </li> <li> <a class="text-decoration-none" href="#Destruction">Destruction</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#TODO">TODO</a> </li> <li> <a class="text-decoration-none" href="#KNOWN-BUGS">KNOWN BUGS</a> </li> <li> <a class="text-decoration-none" href="#AUTHORS">AUTHORS</a> </li> </ul> <h1 id="NAME"><a class="permalink" href="#NAME">#</a>NAME</h1> <p>perlclass - Perl class syntax reference</p> <h1 id="SYNOPSIS"><a class="permalink" href="#SYNOPSIS">#</a>SYNOPSIS</h1> <pre><code>use v5.38; use feature 'class'; class My::Example 1.234 { field $x; ADJUST { $x = "Hello, world"; } method print_message { say $x; } } My::Example->new->print_message;</code></pre> <h1 id="DESCRIPTION"><a class="permalink" href="#DESCRIPTION">#</a>DESCRIPTION</h1> <p>This document describes the syntax of Perl's <code>class</code> feature, which provides native keywords for object-oriented programming.</p> <h2 id="History"><a class="permalink" href="#History">#</a>History</h2> <p>Since Perl 5, support for objects revolved around the concept of <i>blessing</i> references with a package name (see <a href="/blead/perlfunc#bless-REF%2CCLASSNAME">"bless REF,CLASSNAME" in perlfunc</a>). Such a reference could then be used to call subroutines from the package it was blessed with (or any of its parents). This system, while bare-bones, was flexible enough to allow creation of multiple more advanced, community-driven systems for object orientation. For more information, see <a href="/blead/perlmod">perlmod</a> and <a href="/blead/perlobj">perlobj</a>.</p> <p>The <code>class</code> feature is a core implementation of a class syntax that is similar to what one would find in other programming languages. It is not a wrapper around <code>bless</code>, but a completely new system built right into the perl interpreter.</p> <h1 id="KEYWORDS"><a class="permalink" href="#KEYWORDS">#</a>KEYWORDS</h1> <p>Enabling the <code>class</code> feature allows the usage of the following new keywords in the current lexical scope:</p> <h2 id="class"><a class="permalink" href="#class">#</a>class</h2> <pre><code>class NAME BLOCK class NAME VERSION BLOCK class NAME VERSION : ATTRIBUTES... BLOCK class NAME; class NAME VERSION; class NAME VERSION : ATTRIBUTES...;</code></pre> <p>The <code>class</code> keyword declares a new package (see <a href="/blead/perlmod#Packages">"Packages" in perlmod</a>) that is intended to be a class. All other keywords from the <code>class</code> feature should be used within the scope of this declaration.</p> <pre><code>class WithVersion 1.000 { # class definition goes here }</code></pre> <p>Classes can be declared in either block or statement syntax. If a block is used, the body of the block contains the implementation of the class. If the statement form is used, the remainder of the current scope or file is used up until the next <code>class</code> or <code>package</code> statement.</p> <p>A <code>class</code> declaration can optionally have a version number, similar to the <code>package</code> keyword. It can also optionally have attributes. If both are specified, the version number must come first, before the attributes.</p> <p><code>class</code> and <code>package</code> declarations are similar, but classes automatically get a constructor named <code>new</code> - you don't have to (and should not) write one. Additionally, in the class BLOCK you are allowed to declare fields and methods.</p> <h2 id="field"><a class="permalink" href="#field">#</a>field</h2> <pre><code>field VARIABLE_NAME; field VARIABLE_NAME = EXPR; field VARIABLE_NAME : ATTRIBUTES; field VARIABLE_NAME : ATTRIBUTES = EXPR;</code></pre> <p>Fields are variables that are visible in the scope of the class - more specifically within <a href="#method">"method"</a> and <a href="#Adjustment">ADJUST</a> blocks. Each class instance gets its own storage of fields, independent of other instances.</p> <p>A field behaves like a normal lexically scoped variable. It has a sigil and is private to the class (though creation of an accessor method will make it accessible from the outside). The main difference is that different instances access different values in the same scope.</p> <pre><code>class WithFields { field $scalar = 42; field @array = qw(this is just an array); field %hash = (species => 'Martian', planet => 'Mars'); }</code></pre> <p>Fields may optionally have initializing expressions. If present, the expression will be evaluated within the constructor of each object instance. During each evaluation, the expression can use the value of any previously-set field, as well as any other variables in scope.</p> <pre><code>class WithACounter { my $next_count = 1; field $count = $next_count++; }</code></pre> <p>When combined with the <code>:param</code> field attribute, the defaulting expression can use any of the <code>=</code>, <code>//=</code> or <code>||=</code> operators. Expressions using <code>=</code> will apply whenever the caller did not pass the corresponding parameter to the constructor at all. Expressions using <code>//=</code> will also apply if the caller did pass the parameter but the value was undefined, and expressions using <code>||=</code> will apply if the value was false.</p> <p>During a field initializing expression, the instance is not yet constructed and so the <code>$self</code> lexical is not available. However, the special <code>__CLASS__</code> token may be used to obtain the name of the class being constructed, for example in order to invoke class methods on it to help in constructing values for fields.</p> <pre><code>class WithCustomField { use constant DEFAULT_X => 10; field $x = __CLASS__->DEFAULT_X; }</code></pre> <p>This allows subclasses to override the method with different behaviour.</p> <pre><code>class DifferentCustomField :isa(WithCustomField) { sub DEFAULT_X { rand > 0.5 ? 20 : 30 } }</code></pre> <p>When an instance of <code>DifferentCustomField</code> is constructed, the <code>__CLASS__</code> expression in the base will yield the correct class name, and so invoke this overridden method instead.</p> <h2 id="method"><a class="permalink" href="#method">#</a>method</h2> <pre><code class="plaintext">method METHOD_NAME SIGNATURE BLOCK method METHOD_NAME BLOCK method SIGNATURE BLOCK method BLOCK</code></pre> <p>Methods are subroutines intended to be called in the context of class objects.</p> <p>A variable named <code>$self</code> populated with the current object instance will automatically be created in the lexical scope of <code>method</code>.</p> <p>Methods always act as if <code>use feature 'signatures'</code> is in effect, but <code>$self</code> will not appear in the arguments list as far as the signature is concerned.</p> <pre><code>class WithMethods { field $greetings; ADJUST { $greetings = "Hello"; } method greet($name = "someone") { say "$greetings, $name"; } }</code></pre> <p>Just like regular subroutines, methods <i>can</i> be anonymous:</p> <pre><code>class AnonMethodFactory { method get_anon_method { return method { return 'this is an anonymous method'; }; } }</code></pre> <p>Methods can also be declared as lexical subroutines, using the <code>my</code> prefix. This creates a subroutine that is lexically visible within the current scope, but does not appear in the symbol table. The effect is that of a <i>private</i> method; one that can be called from within the class's own code, but not from outside.</p> <p>To invoke these lexical subroutines as methods, it is best to use the <code>->&</code> operator. This bypasses method lookup by name, and directly invokes a lexical subroutine as if it was a method.</p> <pre><code>class LexicalMethod { my method abc ($x, $y) { say "Internal method abc invoked with x=$x y=$y"; } method xyz { $self->&abc("x", "y"); } } # The `abc` method is not visible from here</code></pre> <h1 id="ATTRIBUTES"><a class="permalink" href="#ATTRIBUTES">#</a>ATTRIBUTES</h1> <p>Specific aspects of the keywords mentioned above are managed using <i>attributes</i>. Attributes all start with a colon, and one or more of them can be appended after the item's name, separated by a space.</p> <h2 id="Class-attributes"><a class="permalink" href="#Class-attributes">#</a><a id="Class"></a>Class attributes</h2> <h3 id=":isa"><a class="permalink" href="#:isa">#</a><a id="isa"></a>:isa</h3> <p>Classes may inherit from <b>one</b> superclass, by using the <code>:isa</code> class attribute.</p> <pre><code class="plaintext">class Example::Base { ... } class Example::Subclass :isa(Example::Base) { ... }</code></pre> <p>Inherited methods are visible and may be invoked. Fields are always lexical and therefore not visible by inheritance.</p> <p>The <code>:isa</code> attribute may request a minimum version of the base class. As with <code>use MODULE VERSION</code>, if the actual version of the base class is too low, compilation will fail.</p> <pre><code class="plaintext">class Example::Subclass :isa(Example::Base 2.345) { ... }</code></pre> <p>The <code>:isa</code> attribute will attempt to <code>require</code> the named module if it is not already loaded.</p> <h2 id="Field-attributes"><a class="permalink" href="#Field-attributes">#</a><a id="Field"></a>Field attributes</h2> <h3 id=":param"><a class="permalink" href="#:param">#</a><a id="param"></a>:param</h3> <p>A scalar field with a <code>:param</code> attribute will take its value from a named parameter passed to the constructor. By default the parameter will have the same name as the field (minus its leading <code>$</code> sigil), but a different name can be specified in the attribute.</p> <pre><code>field $x :param; field $y :param(the_y_value);</code></pre> <p>If there is no defaulting expression, then the parameter is required by the constructor; the caller must pass it or an exception is thrown. With a defaulting expression this becomes optional.</p> <h3 id=":reader"><a class="permalink" href="#:reader">#</a><a id="reader"></a>:reader</h3> <p>A field with a <code>:reader</code> attribute will generate a reader accessor method automatically. The generated method will have an empty (i.e. zero-argument) signature, and its body will simply return the value of the field variable.</p> <pre><code>field $s :reader; # Equivalent to field $s; method s () { return $s; }</code></pre> <p>By default the accessor method will have the same name as the field (minus the leading sigil), but a different name can be specified in the attribute's value.</p> <pre><code>field $x :reader(get_x); # Generates a method method get_x () { return $x; }</code></pre> <p>Reader methods can be applied to non-scalar fields. When invoked in list context, they yield the contents of the field; in scalar context they yield the count of elements, as if the field variable had been placed in scalar context.</p> <pre><code>field @users :reader; ... scalar $instance->users;</code></pre> <h3 id=":writer"><a class="permalink" href="#:writer">#</a><a id="writer"></a>:writer</h3> <p>A field with a <code>:writer</code> attribute will generate a writer accessor method automatically. The generated method will have a signature that consumes exactly one argument, and its body will assign that scalar argument to the field and return the invocant object itself.</p> <pre><code>field $s :writer; # Equivalent to field $s; method set_s($new) { $s = $new; return $self; }</code></pre> <p>By default the accessor method will have the name of the field minus the leading sigil with the string <code>set_</code> prefixed to it, but a different name can be specified in the attribute's value.</p> <pre><code>field $x :writer(write_x); # Generates a method method write_x ($new) { ... }</code></pre> <p>Currently, writer accessors can only be applied to scalar fields. Attempts to apply this attribute to a non-scalar field will result in a fatal exception at compile-time. This may be relaxed in a future version to allow writers on array or hash fields. For now, these will have to be created manually.</p> <h2 id="Method-attributes"><a class="permalink" href="#Method-attributes">#</a><a id="Method"></a>Method attributes</h2> <p>None yet.</p> <h1 id="OBJECT-LIFECYCLE"><a class="permalink" href="#OBJECT-LIFECYCLE">#</a><a id="OBJECT"></a>OBJECT LIFECYCLE</h1> <h2 id="Construction"><a class="permalink" href="#Construction">#</a>Construction</h2> <p>Each object begins its life with a constructor call. The constructor is always named <code>new</code> and is invoked like a method call on the class name:</p> <pre><code>my $object = My::Class->new(%arguments);</code></pre> <p>During object construction, class fields are looked up in the <code>%arguments</code> hash and populated where possible.</p> <h2 id="Adjustment"><a class="permalink" href="#Adjustment">#</a>Adjustment</h2> <p>Object adjustment is a way to run arbitrary user-defined code during object construction. This is done by placing code in <code>ADJUST</code> blocks. Every time an object is constructed, its <code>ADJUST</code> blocks are executed (in the order in which they are declared).</p> <pre><code>class WellAdjusted { field $x :param; ADJUST { say "Hello!"; } ADJUST { say "x = $x"; } } my $object = WellAdjusted->new(x => 42); # Output: # Hello! # x = 42</code></pre> <p><code>ADJUST</code> blocks are syntactically similar to <a href="/blead/perlmod#BEGIN%2C-UNITCHECK%2C-CHECK%2C-INIT-and-END"><code>BEGIN</code> or <code>INIT</code> blocks</a>, which only run once. However, <code>ADJUST</code> blocks, like methods, have access to <code>$self</code> (a lexical variable holding the object being constructed) as well as all object fields created up to that point.</p> <h2 id="Lifetime"><a class="permalink" href="#Lifetime">#</a>Lifetime</h2> <p>After the construction phase, the object is ready to be used.</p> <p>Using <code>blessed</code> (<code>Scalar::Util::blessed</code> or <code>builtin::blessed</code>) on the object will return the name of the class, while <code>reftype</code> (<code>Scalar::Util::reftype</code> or <code>builtin::reftype</code>) will return the string <code>'OBJECT'</code>.</p> <h2 id="Destruction"><a class="permalink" href="#Destruction">#</a>Destruction</h2> <p>An object is destroyed when the last reference to it goes away, just as with other data structures in Perl.</p> <h1 id="TODO"><a class="permalink" href="#TODO">#</a>TODO</h1> <p>This feature is still experimental and very incomplete. The following list gives an overview of features still to be added or changed:</p> <ul> <li><p>Roles</p> <p>Some syntax for declaring a role (likely a <code>role</code> keyword), and for consuming a role into a class (likely a <code>:does()</code> attribute).</p> </li> <li><p>Parameters to ADJUST blocks</p> <p>Some syntax for declaring that an <code>ADJUST</code> block can consume named parameters, which become part of the class constructor's API. This might be inspired by a similar plan to add named arguments to subroutine signatures.</p> <pre><code>class X { ADJUST (:$alpha, :$beta = 123) { ... } } my $obj = X->new(alpha => 456);</code></pre> </li> <li><p>ADJUST blocks as true blocks</p> <p>Currently, every ADJUST block is wrapped in its own CV (subroutine) that gets invoked with the full ENTERSUB overhead. It should be possible to use the same mechanism that makes all field initializer expressions appear within the same CV on ADJUST blocks as well, merging them all into a single CV per class. This will make it faster to invoke if a class has more than one of them.</p> </li> <li><p>More accessor generator attributes</p> <p>Attributes to request that other kinds of accessor methods be generated for fields. Likely <code>:writer</code>.</p> <pre><code>class X { field $name :writer; }</code></pre> <p>Equivalent to</p> <pre><code>class X { field $name; method set_name ($new) { $name = $new; return $self; } }</code></pre> </li> <li><p>Metaprogramming</p> <p>An extension of the metaprogramming API (currently proposed by <a href="https://github.com/Perl/PPCs/pull/25">PPC0022</a>) which adds knowledge of classes, methods, fields, ADJUST blocks, and other such class-related details.</p> </li> <li><p>Extension Customisation</p> <p>Ways in which out-of-core modules can interact with the class system, including an ability for them to provide new class or field attributes.</p> </li> </ul> <h1 id="KNOWN-BUGS"><a class="permalink" href="#KNOWN-BUGS">#</a><a id="KNOWN"></a>KNOWN BUGS</h1> <p>The following bugs have been found in the experimental <code>class</code> feature:</p> <ul> <li><p>Since Perl v5.38, inheriting from a parent class which is declared in the same file and which hadn't already been sealed can cause a segmentation fault. [<a href="https://github.com/Perl/perl5/issues/20890">GH #20890</a>]</p> </li> <li><p>Since Perl v5.38 and with the experimental <code>refaliasing</code> feature, trying to replace a field variable causes a segmentation fault. [<a href="https://github.com/Perl/perl5/issues/20947">GH #20947</a>]</p> </li> <li><p>Since Perl v5.38, it's possible to craft a class with leaky encapsulation, which can cause a segmentation fault. [<a href="https://github.com/Perl/perl5/issues/20956">GH #20956</a>]</p> </li> <li><p>In Perl v5.38, inheriting from a class would not always attempt to load the parent class (fixed in Perl v5.40). [<a href="https://github.com/Perl/perl5/issues/21332">GH #21332</a>]</p> </li> </ul> <h1 id="AUTHORS"><a class="permalink" href="#AUTHORS">#</a>AUTHORS</h1> <p>Paul Evans</p> <p>Bartosz Jarzyna</p> </div> <div id="footer"> <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p> <p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> <script src="/js/highlight.pack.js"></script> <script>hljs.highlightAll();</script> </body> </html>